hammer.js-》移動端事件監測
阿新 • • 發佈:2022-06-01
描述
給定兩個字串str1和str2,輸出兩個字串的最長公共子串 題目保證str1和str2的最長公共子串存在且唯一。 資料範圍: 1 \le |str1|,|str2| \le 50001≤∣str1∣,∣str2∣≤5000要求: 空間複雜度 O(n^2)O(n2),時間複雜度 O(n^2)O(n2)
示例1
輸入:"1AB2345CD","12345EF"返回值:
"2345"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 int len1 = str1.length(); int len2 = str2.length(); String commonStr = ""; int commonLen = 0; for(int i=0; i<len1; i++){ char temp = str1.charAt(i); if(commonLen>(len1-i)){ return commonStr; } for(int j=0; j<len2;j++){ int tmpCommonLen = 0; String tmpCommonStr = ""; int k1 = i; int k2 = j; while(k1<len1&&k2<len2&&str1.charAt(k1)==str2.charAt(k2)){ tmpCommonLen ++; tmpCommonStr += str1.charAt(k1); k1++; k2++; } if(commonLen<tmpCommonLen){ commonLen = tmpCommonLen; commonStr = tmpCommonStr; } } } return commonStr; } }