题解 | #查找两个字符串a,b中的最长公共子串#

查找两个字符串a,b中的最长公共子串

http://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506

java dp

import java.util.*;
public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            while(sc.hasNextLine()) {
                String a = sc.nextLine();
                String b = sc.nextLine();
                String longStr = (a.length() > b.length())? a:b;
                String shortStr = (a.length() < b.length())? a:b;
                int[][] dp = new int[shortStr.length()+1][longStr.length()+1];
                int res = 0;
                int index = 0;
                for (int i = 1; i <= shortStr.length(); i++ ) {
                    for (int j = 1; j <= longStr.length(); j++) {
                        if (shortStr.charAt(i-1) == longStr.charAt(j - 1)) {
                            dp[i][j] = dp[i-1][j-1] +1;
                            if (dp[i][j] > res) {
                                res = dp[i][j];
                                index = i;
                            }
                        } 
                    }
                    
                }
                
                if (res > 0) {
                    System.out.println(shortStr.substring(index - res,index));
                }
            }
        }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
今天 12:11
我最近都有点不想活了,天天早10晚11的,还问我爱不爱她目前的状态别说爱谁了,没扇谁就不错了。是不是大家都是一进节子,只有工作没有爱情了
AzureSkies:在字节的时候找的就是字节的,飞书太适合恋爱人士了,能看到是不是已读,是不是在会议中。简直冥婚好伴侣
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
05-29 09:02
门头沟学院 Java
点赞 评论 收藏
分享
评论
3
1
分享

创作者周榜

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