1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| public class StringDemo2 {
public String getMaxSameString(String str1,String str2){ if(str1 != null && str2 != null){ String maxStr = (str1.length() >= str2.length())? str1 : str2; String minStr = (str1.length() < str2.length())? str1 : str2; int length = minStr.length();
for(int i = 0;i < length;i++){ for(int x = 0,y = length - i;y <= length;x++,y++){ String subStr = minStr.substring(x,y); if(maxStr.contains(subStr)){ return subStr; }
} }
} return null; }
public String[] getMaxSameString1(String str1, String str2) { if (str1 != null && str2 != null) { StringBuffer sBuffer = new StringBuffer(); String maxString = (str1.length() > str2.length()) ? str1 : str2; String minString = (str1.length() > str2.length()) ? str2 : str1;
int len = minString.length(); for (int i = 0; i < len; i++) { for (int x = 0, y = len - i; y <= len; x++, y++) { String subString = minString.substring(x, y); if (maxString.contains(subString)) { sBuffer.append(subString + ","); } }
if (sBuffer.length() != 0) { break; } } String[] split = sBuffer.toString().replaceAll(",$", "").split("\\,"); return split; }
return null; }
@Test public void testGetMaxSameString(){ String str1 = "abcwerthello1yuiodefabcdef"; String str2 = "cvhello1bnmabcdef"; String[] maxSameStrings = getMaxSameString1(str1, str2); System.out.println(Arrays.toString(maxSameStrings));
}
}
|