"1AB2345CD","12345EF"
"2345"
import java.util.*; public class Solution { /** * longest common substring * @param str1 string字符串 the string * @param str2 string字符串 the string * @return string字符串 */ //状态记录,取缔二维数组,减少内存开销 int start = 0; int stepNum = 0; int currentStart = 0; int currentStepNum = 0; boolean cancleLeft = false; boolean cancleRight = false; int len2 = 0; public String LCS (String str1, String str2) { String breakJudge; if (str1.length() < str2.length()){ String temp = str1; str1 = str2; str2 = temp; } len2 = str2.length(); for (int i = 0;i < str1.length() && !cancleRight;i++){ for (int j = 0; j < str2.length() && i + j < str1.length();j++) doJudge(str1,str2,j + i,j); clear(); if (!cancleRight) cancleRight = breakJudge(str1.length(),i); } clear(); for (int i = 0;i < str2.length() && ! cancleLeft;i++){ for (int j = 0; i + j < str2.length();j++) doJudge(str1,str2,j,j + i); clear(); if (!cancleLeft) cancleLeft = breakJudge(str2.length(),i); } return stepNum == 0 ? "-1" : str1.substring(start,start + stepNum); } // 判断能否提前退出 public boolean breakJudge(int len,int i){ if (stepNum == len2 || (stepNum >= (len - i))){ return true; } return false; } public void clear(){ if (currentStepNum > stepNum){ stepNum = currentStepNum; start = currentStart; } currentStepNum = 0; currentStart = 0; } public void doJudge(String str1,String str2,int index1,int index2){ if ( str1.charAt(index1) == str2.charAt(index2)){ if (currentStepNum == 0)// 记录步长为0 currentStart = index1; //更新起点 currentStepNum ++;//步长加一 } else clear();//不等,对比当前步长与缓存步长,更新保存的步长与起点 } }
这道题你会答吗?花几分钟告诉大家答案吧!
扫描二维码,关注牛客网
下载牛客APP,随时随地刷题