1. 程式人生 > >Leecode 14. 最長公共字首

Leecode 14. 最長公共字首

編寫一個函式來查詢字串陣列中的最長公共字首。

如果不存在公共字首,返回空字串 “”。
示例 1:

輸入: ["flower","flow","flight"]
輸出: "fl"
示例 2:

輸入: ["dog","racecar","car"]
輸出: ""
解釋: 輸入不存在公共字首。
說明:

所有輸入只包含小寫字母 a-z 。

AC:

使用startWith() 判斷字首,substring一直擷取

class Solution {
   public static String longestCommonPrefix(String[] strs) {
        int count = strs.length;
        String prefix = "";
        if(count != 0){
            prefix = strs[0];
        }
        for(int i=0; i<count; i++){
            while(!strs[i].startsWith(prefix)){
                prefix = prefix.substring(0, prefix.length()-1);
            }
        }
        return prefix;
    }

}