博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode OJ - Interleaving String
阅读量:7219 次
发布时间:2019-06-29

本文共 1876 字,大约阅读时间需要 6 分钟。

这道题用DP来解决,也可以用递归,但是时间复杂度很高,被报TLE。

下面是DP的AC代码。

1 /** 2      * Solution 2 :DP Accepted 3      * create a (len1+1) x (len2+1) matrix A, A[i][j] means s3[0...i+j-1] is formed by the interleaving of s1[0...i-1] and s2[0...j-1] 4      * A[i][j] =  True   if A[i-1][j] = true && s3[i+j-1] = s1[i-1] or A[i][j-1] = true && s3[i+j-1] = s2[j-1]; 5      *            False  else 6      * @param s1 7      * @param s2 8      * @param s3 9      * @return10      */11     public boolean isInterleave2(String s1, String s2, String s3){12         int len1 = s1.length();13         int len2 = s2.length();14         int len3 = s3.length();15         16         if(len1+len2!=len3)17             return false;18         19         char[] c1 = s1.toCharArray();20         char[] c2 = s2.toCharArray();21         char[] c3 = s3.toCharArray();22         23         //DP24         boolean[][] A = new boolean[len1+1][len2+1];25         A[0][0] = true;26         for(int i = 1;i<=len1;i++)27             if( A[i-1][0]== true && c3[i-1] == c1[i-1])28                 A[i][0] = true;29             else30                 A[i][0] = false;31         for(int j=1;j<=len2;j++)32             if(A[0][j-1] == true && c3[j-1] == c2[j-1])33                 A[0][j] = true;34             else35                 A[0][j] = false;36         37         for(int i=1;i<=len1;i++){38             for(int j=1;j<=len2;j++){39                 if(A[i-1][j] == false && A[i][j-1] == false)40                     A[i][j] = false;41                 else if(A[i-1][j] == true && c3[i+j-1] == c1[i-1])42                     A[i][j] = true;43                 else if(A[i][j-1] == true && c3[i+j-1] == c2[j-1])44                     A[i][j] = true;45                 else46                     A[i][j] = false;47             }48         }49         return A[len1][len2];50     }

 

转载于:https://www.cnblogs.com/echoht/p/3711243.html

你可能感兴趣的文章
Eclipse打包插件Fat Jar 解压打包
查看>>
Apache Shiro 使用手册
查看>>
CentOS mini 6.5 安装DB2 Express-C 问题处理记录
查看>>
DirectByteBuffer
查看>>
Docker Compose文件详解 V2
查看>>
Memcached的原理与应用(未完)
查看>>
基于 Confluence 6 数据中心的 SAML 单点登录设置你的身份提供者
查看>>
mysql总结
查看>>
Navicat for MySQL版本更新至v11.2.12,修复多项问题|附下载
查看>>
整理 JAVA中的IO流 (字符流和字节流两个大类)
查看>>
uefi与win8 (根据网络资料整理)
查看>>
Eclipse优化
查看>>
Log4j tutorial with Tomcat examples
查看>>
Kong 网关
查看>>
三层结构视频中的DBHelper.cs
查看>>
[转载] 信息系统项目管理师视频教程——18 项目沟通管理
查看>>
在Windows下建立QT开发环境
查看>>
Jedis、JedisPool、ShardedJedis和ShardedJedisPool,java对redis的基本操作
查看>>
[转载] 致命伴侣
查看>>
HTML5 localStorage本地存储实际应用举例
查看>>