publicstaticintlongestCommonSubstring1(String text1, String text2){int[][] dp =newint[text1.length()+1][text2.length()+1];int len =0;for(int i =1; i < text1.length()+1; i++){for(int j =1; j < text2.length()+1; j++){if(text1.charAt(i-1)== text2.charAt(j-1)){
dp[i][j]= dp[i -1][j -1]+1;
len = Math.max(len, dp[i][j]);}}}return len;}
2.2 获取所有的最长公共子字符串
publicstatic List<String>longestCommonSubstring2(String text1, String text2){int[][] dp =newint[text1.length()+1][text2.length()+1];
List<Integer> positions =newArrayList<>();// the ending position of the common substring in text1int len =0;for(int i =1; i < text1.length()+1; i++){for(int j =1; j < text2.length()+1; j++){if(text1.charAt(i-1)== text2.charAt(j-1)){
dp[i][j]= dp[i -1][j -1]+1;if(dp[i][j]> len){
len = dp[i][j];
positions.clear();
positions.add(i);}elseif(dp[i][j]== len && len >0){
positions.add(i);}}}}
Set<String> res =newHashSet<>();// resultfor(int position: positions){
res.add(text1.substring(position-len, position));}return(newArrayList<>(res));}
```