本帖最后由 sisel 于 2015-4-11 23:30 编辑
刚才的方法有2个漏洞 删除
用dp可以做到O(m*n) 级别的效率:
- public static String maxSubString(String st1, String st2) {
- char[] x=st1.toCharArray(),y=st2.toCharArray();
- int maxlen =0, maxindex = 0,xlen=x.length,ylen=y.length;
- int [][] dp=new int[xlen][ylen];
- for (int i = 0; i < xlen; ++i) {
- for (int j = 0; j < ylen; ++j) {
- if (x[i] == y[j]) {
- if (i>0 && j>0) {
- dp[i][j] = dp[i - 1][j - 1] + 1;
- }
- if (i == 0 || j == 0) {
- dp[i][j] = 1;
- }
- if (dp[i][j] > maxlen) {
- maxlen = dp[i][j];
- maxindex = i + 1 - maxlen;
- }
- }
- }
- }
- return new String(x,maxindex,maxlen);
- }
复制代码
|