longest-common-prefix


/**
*編寫一個函數來查找字符串數組中的最長公共前綴。
* 若是不存在公共前綴,返回空字符串 ""。
* 說明: 全部輸入只包含小寫字母 a-z 。
*/

/**
 *編寫一個函數來查找字符串數組中的最長公共前綴。
 * 若是不存在公共前綴,返回空字符串 ""。
 * 說明: 全部輸入只包含小寫字母 a-z 。
 */

public class Main53 {
    public static void main(String[] args) {
        String[] strs = {};
        System.out.println(Main53.longestCommonPrefix(strs));
    }

    public static String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length < 1) {
            return "";
        }
        String result = strs[0];
        for(int i=1; i<strs.length; i++){
            if(!strs[i].startsWith(result)){
                result = result.substring(0, result.length()-1);
                i--;
                // 新的字符串以 整個result 開頭的話繼續循環下去
                // 新的字符串不以 整個result 開頭的話就將result這個字符串最後一位砍掉,並再次比較。
            }
        }
        return result;
    }
}
相關文章
相關標籤/搜索