兩個字符串中最大的公共字串

package 數組;

/*
 *本程序尋找兩個字符串中最大的公共字串,並且考慮到了長度一樣長最大字串。
 *
 * 想法:將一個字串按照從大到小的順序拆開,第一匹配到的一定是最長字串,待該長度字串循環完畢後,停止循環。
 */
public class getMaxCommanString
{
    public static void main(String a[])
    {
	find("hello aasdxzc world", "hello,world"); // 控制檯會輸出 hello world
    }

    private static void find(String str, String key)
    {
	String temp = null;
	int y, z;
	boolean flag = false;
	for (int i = 0; i < str.length(); i++) { // 確定偏移位置。
	    for (y = 0, z = (str.length() - i); z != str.length() + 1; y++, z++) {
		//假如原來是10個字符,循環到i=5時,則先取01234,然後12345直到56789 
                //內層循環能夠按照“第一循環的偏移位置”所確定的長度循環出字串。
		temp = str.substring(y, z);
	        if (key.contains(temp)) {
		    System.out.println(temp);
		    flag = true;
		}
	    }
	    if (flag) {
//這個是在完成一次內層循環時候的判定,flag爲真說明該長度的已經匹配完了,而且有,那麼下面更短的不需要匹配了。
 		break;
	    }
	}
    }
}


 

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