Java基礎面試題——(5)

題目:獲取兩個字符串中最大相同子串。比如: str1 = "abcwerthelloyuiodef“;str2 = "cvhellobnm"。


代碼實現:

public class JavaInterview_5 {
	
	public static String getMaxSameString(String src, String sub){
		
		if(src == null || src.length() == 0){
			return null;
		}
		
		if(sub == null || sub.length() == 0){
			return null;
		}
		
		for(int step = sub.length(); step >= 1; step--){
			for(int start = 0; (start + step) <= sub.length(); start++){
				if(src.contains(sub.substring(start, start + step))){
					return sub.substring(start, start + step);
				}
			}
		}
		
		return null;
	}
	
	public static void main(String[] args) {	
	
		String src = "abcwerthelloyuiodef";
		String sub = "cvhellobnm";
		
		System.out.println(JavaInterview_5.getMaxSameString(src, sub));
	}
}

運行結果:


PS:將短的那個串進行長度依次遞減的子串與較長的串比較。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章