题目
题目主要信息:
- 查找两个字符串str1,str2中的最长的公共子串
- 保证str1和str2的最长公共子串存在且唯一
举一反三:
学习完本题的思路你可以解决如下题目:
方法一:枚举(前置方法,超时,不能完全通过)
思路:
最简单直观的方式大概就是枚举了,枚举所有的子串进行比较,但是太复杂了。其实找子串不用一样完全枚举,还可以尝试改良一下
具体做法:
- step 1:我们完全可以遍历两个字符串的所有字符串作为起始
- step 2:然后同时开始检查字符是否相等,相等则不断后移,增加子串长度,如果不等说明以这两个为起点的子串截止了,不会再有了。
- step 3:后续比较长度维护最大值即可。
图示:

Java实现代码:
import java.util.*;
public class Solution {
public String LCS (String str1, String str2) {
int length = 0;
String res = "";
//遍历s1每个起始点
for(int i = 0; i < str1.length(); i++){
//遍历s2每个起点
for(int j = 0; j < str2.length(); j++){
int temp = 0;
String temps = "";
int x = i, y = j;
//比较每个起点为始的子串
while(x < str1.length() && y < str2.length() && str1.charAt(x) == str2.charAt(y)){
temps += str1.charAt(x);
x++;
y++;
temp++;
}
//更新更大的长度子串
if(length < temp){
length = temp;
res = temps;

最低0.47元/天 解锁文章
2058

被折叠的 条评论
为什么被折叠?



