最长公共前缀

class Solution {
public:
   string longestCommonPrefix(vector<string>& strs) {
       if(strs.empty()) 
           return "";
       if(strs.size() == 1) 
           return strs[0];
       
       string prefix = strs[0];
       for(int i = 1; i < strs.size(); i++)
       {
            int LastIndex = min(prefix.length(),strs[i].length());
            for(int j = 0; j < LastIndex; j++)
            {
                if(prefix[j] != strs[i][j])
                {
                    LastIndex = j;
                    break;
                }
            }
           prefix = prefix.substr(0,LastIndex);
       }
       return prefix;
    }
};

 思路:维护一个 prefix 是当前最长公共前缀,然后依次和后面所有的串比较,更新 prefix。直到遍历strs结束。

原文地址:https://www.cnblogs.com/stul/p/10682179.html