【Java練習】獲取兩個字串中最長的相同欄位
阿新 • • 發佈:2018-12-02
獲取兩個字串中最長的子串並輸出。
思路解析:
1.首先考慮我們要知道長度最短的字串,這樣子在比較的次數會更少。
2.我們首先從長度最小的字串每次擷取一小段判斷是否在大串中
3.考慮到有可能有多個長度相同的子串,那麼我們就應該將他們同時儲存到集合中
4.要多考慮到各種異常的發生。
以下是我寫的程式碼,主要用於練習用,不喜勿噴,歡迎指正,謹以此溫習Java基礎。
package com.yaml.procties; import java.util.ArrayList; import java.util.List; /** * @author * @date * @version * @Description 獲取兩個字串具有最大共同的子串 */ public class GetMaxComStr { public static void main(String[] args) { String str1 = "abcxxaddfnnn"; String str2 = "aabcddaddgnnn"; List<String> theMaxComStr = getTheMaxComStr(str1, str2); if(theMaxComStr != null || theMaxComStr.size()> 0){ System.out.println(theMaxComStr.toString()); } } /** * @author * @date * @parameter str1:表示待比較的第一個字串 str2:表示待比較的第二個字串 * @return 共同的最大的子串 * @throws @override */ public static List<String> getTheMaxComStr(String str1, String str2) { if(str1 == null || str2 == null || str1.isEmpty() || str2.isEmpty()){ return null; } String max = str1.length() >= str2.length() ? str1 : str2; String min = max == str1 ? str2 : str1; String theMaxComStr = ""; boolean isNewComStr = true; List<String> maxComList = null; for (int i = 0; i < min.length(); i++) { for (int j = 0; j < min.length() - i; j++) { String subStr = min.substring(i, i + j + 1); if (isNewComStr) { maxComList = new ArrayList<String>(); maxComList.add(theMaxComStr); isNewComStr = false; } if (max.indexOf(subStr) != -1) { if (theMaxComStr.length() < subStr.length()) { theMaxComStr = subStr; isNewComStr = true; } if (theMaxComStr.length() == subStr.length()) maxComList.add(subStr); } } } return maxComList; } }