LeetCode #14 简单题(多字符串的最长公共前缀)

题目: 求多个字符串的最长公共前缀。

题解: 都跟第一个字符串比一下就行了,注意字符串长度边界。

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        int n = (int)strs.size();
        if (n == 0)return "";
        if (n == 1)return strs[0];

        int index = 0;
        while(true){
            bool findIndex = false;
            for (int i = 1; i < n; ++i){
                if (index >= strs[i].size() || 
                    index >= strs[0].size() || 
                    strs[i][index] != strs[0][index]){
                    findIndex = true;
                    break;
                }
            }
            if (findIndex) break;
            index ++;
        }
        return strs[0].substr(0, index);
    }
};

猜你喜欢

转载自www.cnblogs.com/error408/p/11651183.html