1. 程式人生 > >[Leetcode]Q14練習記錄

[Leetcode]Q14練習記錄

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

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

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        n = len(strs)
        lenList = []
        if n == 0:
            return ""
        if n == 1:
            return strs[0]
        for i in range(n):
            lenList.append(len(strs[i]))
        sortLen = sorted(lenList)
        strComp = strs[lenList.index(sortLen[0])]
        res = ""
        for i in range(sortLen[0]):
            strO = strComp[i]
            for j in range(n):
                temp = strs[j]
                if temp[i] != strO:
                    return res
            res += strO
        return res
            
        

 python程式碼還可以精簡,C++程式碼執行之後時間開銷比較大還可以優化

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        int n = strs.size();
        if(n == 0) return "";
        if(n == 1) return strs[0];
        int minLen = strs[0].length();
        string Compare = strs[0];
        for(int i = 0;i < n;i++){
            if(strs[i].length() < minLen){
                minLen = strs[i].length();
                Compare = strs[i];
            }
        }
        string res = "";
        for(int i=0;i<minLen;i++){
            char temp = Compare[i];
            for(int j=0;j<n;j++){
                string test = strs[j];
                if(test[i] != temp) return res;
            }
            res += temp;
        }
        return res;
    }
};