# leetcode #[14. 最長公共前綴]

leetcode

14. 最長公共前綴

class Solution {
    public String longestCommonPrefix(String[] strs) {
        
        int length = strs.length;
        if(length == 0){
            return "";
        }        

        // 記錄最長公共前綴的位置
        int end = 0;
        boolean same = true;
        
        // 如果每個單詞對應位置的字符相同 且 end的位置沒有越界
        while(same && strs[0].length() > end){

            // 獲取第一個單詞的對應字母,分別和其他單詞進行比較
            char first = strs[0].charAt(end);
            for(String str : strs){
                // 如果單詞已經全部匹配結束 或者 單詞的end位置字母不匹配
                // 說明整個匹配過程已經結束
                if(str.length() == end || str.charAt(end) != first){
                    same = false;
                    break;
                }
            }
            // 只有same爲true,end纔可以繼續+1
            if(same){
                end++;
            }
            
        }

        return strs[0].substring(0, end);

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