LeetCode Longest Common Prefix

 1 class Solution {
 2 public:
 3     string longestCommonPrefix(vector<string> &strs) {
 4         if (strs.size() == 0) return "";
 5         string commstr = strs[0];
 6         for (int i=1; i<strs.size(); i++) {
 7             string& s = strs[i]; 
 8             int k = 0;
 9             while (k<s.size() && k<commstr.size() && s[k] == commstr[k]) k++;
10             commstr = commstr.substr(0, k);if(k == 0) break;
11         }
12         return commstr;
13     }
14 };

是否有更有效的方法呢?

第二轮:

Write a function to find the longest common prefix string amongst an array of strings.

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        string prefix;
        
        if (strs.size() < 1) {
            return prefix;
        }
        int idx = 0;
        for(;idx<strs[0].size(); idx++) {
            bool right = true;
            
            for (int i=1; i<strs.size(); i++) {
                if (strs[0][idx] != strs[i][idx]) {
                    right = false;
                    break;
                }
            }
            if (!right) {
                break;
            } else {
                prefix.push_back(strs[0][idx]);
            }
        }
        
        return prefix;
    }
};
原文地址:https://www.cnblogs.com/lailailai/p/3642015.html