兩個字符串中最長公共子字符串

如"abcde" "bkcdq" 最大公共子字符串是"cd"

public static void findMaxCommonStr(){
		Scanner s =  new Scanner(System.in);
		String str1 = s.next();
		String str2 = s.next();
		
		char a[] = str1.toCharArray();
		char b[] = str2.toCharArray();
		
		int maxlen = 0;		
		int startIndex=0;
		int endIndex = 0;
		
		for(int i=0;i<b.length;i++){//對於b數組中的每一個數組,從第一個開始分別與a中的值比較
			int nowstartIndex = i;
			int nowendIndex = i;
			int tempb = i;///定義序列相同時,b下標當前值,如果直接使用i++,會造成下一個字符開始的遍歷錯誤
			int nowlen = 0;
			boolean flag = false;
			for(int j=0; j<a.length && tempb < b.length; j++){//臨時值不能超過b長度
				if(b[tempb] == a[j]){
					nowendIndex = tempb;
					nowlen = nowendIndex - nowstartIndex;
					tempb++;
					flag = true;
				}else{
					if(flag == true){//如果之前的相同,再遇到一個不相同的字符,後面的不用再比較
						break;
					}//if
				}//else
			}//for
			if(nowlen > maxlen){
				maxlen = nowlen;
				startIndex = nowstartIndex;
				endIndex = nowendIndex;
			}
		}//for
		for(int k=startIndex;k<=endIndex;k++){
			System.out.print(b[k]);
		}
		
}


發佈了61 篇原創文章 · 獲贊 114 · 訪問量 42萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章