標籤:def 公用子串 bubuko oid sys img current bcd bst
要求:求兩個字串的最長公用子串,如“abcdefg”和“adefgwgeweg”的最長公用子串為“defg”(子串必須是連續的)
public class Main03{// 求解兩個字元號的最長公用子串public static String maxSubstring(String strOne, String strTwo){// 參數檢查if(strOne==null || strTwo == null){return null;}if(strOne.equals("") || strTwo.equals("")){return null;}// 二者中較長的字串String max = "";// 二者中較短的字串String min = "";if(strOne.length() < strTwo.length()){max = strTwo;min = strOne;} else{max = strTwo;min = strOne;}String current = "";// 遍曆較短的字串,並依次減少短字串的字元數量,判斷長字元是否包含該子串for(int i=0; i<min.length(); i++){for(int begin=0, end=min.length()-i; end<=min.length(); begin++, end++){current = min.substring(begin, end);if(max.contains(current)){return current;}}}return null;}public static void main(String[] args) {String strOne = "abcdefg";String strTwo = "adefgwgeweg";String result = Main03.maxSubstring(strOne, strTwo);System.out.println(result);}}
總覺得這題,輸出結果和題意不相符合,結果2,是不是把B序列翻轉,求出兩者最長公用子串
求兩個字串的最長公用子串——Java實現