1 public class TestsonString { 2 public static void main(String[] args) { 3 String s1 = "asdfkljasdCCTVCCTVfioejsdfunbsdfhh"; 4 String s2 = "asdfkasdiCCTVCCTVufasdfjh"; 5 sonStringOperation(s1,s2); 6
7 System.out.println("\n================================================"); 8 String s3 = "abcdefgdcba";
9 String s4 = "asdabcdfkasdiCCTVCCTVufasdfdcbajh";10 sonStringOperation(s3,s4);11 } 12 private static void sonStringOperation(String s1,String s2) { 13 if(s1 == null || s2 == null || s1.length() == 0 || s2.length() == 0)
14 return; 15 String temp,s3; 16 if (s1.length() < s2.length()) {// 比較s1與s2長度,將較長的字符串賦給s1
17 temp = s2; 18 s2 = s1; 19 s1 = temp; 20 } 21 int count = s2.length();// 將較短字符串的長度賦值給count
22 int sum = (count + 1) * count / 2;// 計算得出所有可能結果的最大值sum
23 String[] sonArray = new String[sum];// 分配sum個空間給sonArray數組
24 int arrIndex = 0;// sonArray數組下標
25 if (s1.contains(s2)) { 26 System.out.println("最大子字符串為" + s2); 27 } else if (!s1.contains(s2)) { 28 for (int i = 0; i < s2.length(); i++) { 29 for (int j = s2.length(); j > i; j--) { 30 s3 = s2.substring(i, j);// 將截取后的字符串賦值給s3
31 if (s1.contains(s3)) {// 如果s3為s1的子字符串,則將s3置入sonArray數組中
32 sonArray[arrIndex] = s3; 33 arrIndex++; 34 } 35 } 36 } 37 if (sonArray[0] == null) {// 如果sonArray數組為空
38 System.out.println("兩個字符串之間沒有相同的子字符串!"); 39 return; 40 } 41 temp = sonArray[0]; 42 count = 0; 43 for (int i = 1; i < arrIndex; i++) { 44 if (temp.length() < sonArray[i].length()) { 45 temp = sonArray[i]; 46 count = 1; 47 }else if(temp.length() == sonArray[i].length()) { 48 count++; 49 } 50 } 51 System.out.print("兩個字符串的相同的最大子字符串為:"); 52 for (int i = 0; i < arrIndex; i++) { 53 if(temp.length()==sonArray[i].length()) 54 System.out.print(sonArray[i]+" "); 55 } 56 } 57 } 58 }