题解 | #最长公共子串#

最长公共子串

http://www.nowcoder.com/practice/f33f5adc55f444baa0e0ca87ad8a6aac

import java.util.*;


public class Solution {
    /**
     * longest common substring
     * @param str1 string字符串 the string
     * @param str2 string字符串 the string
     * @return string字符串
     */
    public String LCS (String str1, String str2) {
        // write code here
        char[] char1 = str1.toCharArray();
        char[] char2 = str2.toCharArray();
        int len1 = char1.length;
        int len2 = char2.length;
        int[][] dp = new int[len1 + 1][len2 + 1];
        int maxLength = 0;
        int maxLastIndex = 0;
        for(int i = 0; i < len1; i++){
            for(int j = 0; j < len2; j++){
                if(char1[i] == char2[j]){
                    // 依赖于前一次的判断结果,对角线就是指的两个字符串各向前移动一位的字符,如果前面也有相同,在基础上再加一。
                    dp[i + 1][j + 1] = dp[i][j] + 1;
                    if(dp[i + 1][j + 1] > maxLength){
                        maxLength = dp[i + 1][j + 1];
                        maxLastIndex = i;
                    }
                }
                else{
                    dp[i + 1][j + 1] = 0;
                }

            }
        }
        return str1.substring(maxLastIndex - maxLength + 1, maxLastIndex + 1);
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
想去毕业旅行的斑马在...:学校不是92的话,没有实习经历投不了大厂,去投中小厂,拿点实习经历
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务