求兩個字符串的最長公共子串——Java實現


要求:求兩個字符串的最長公共子串,如“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序列翻轉,求出兩者最長公共子串


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM