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

leetcode14. 最長公共字首

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

如果不存在公共字首,返回空字串 ""

示例 1:

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

示例 2:

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

說明:

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

思路:尋找最長的公共子串,那麼尋找到最小長度的子串,與其他子串逐一比較,如果其他子串都有這個子串,那麼返回這個最小字串,如果不含有,那麼最小子串就可自減 1 ,直到為 0 ,還是沒匹配到的話,就返回為 ""。

class Solution {
    public String longestCommonPrefix(String[] strs) {
       if(strs.length == 0){
            return "";
        }
        int min = Integer.Max_value;
        String minStr = "";
        for(int i = 0;i < strs.length; i++){
              if(min > strs[i].length()){
                    min = strs[i].length();
                    minStr = strs[i];
                }  
          }

        for(int i = min;i > 0;i--){
            String temp = minStr.subString(0,i);
            int j;
            for(j = 0;j < strs.length();j++){
                    if(strs[j].subString(0,i).equals(temp)){
                            continue;
                      }else{
                          break;
                    }
                }
                if(j == strs.length){
                        return temp;
                } 
           }
            return "";
	}
}