首页 > 代码库 > Longest common prefix | leetcode

Longest common prefix | leetcode

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

思路:要去是寻找字符串vector里最长的公有前缀。

1。构造迭代器,遍历vector搜索最小string长度。然后从第一个字符开始进行遍历,如果遇到不一样的字符即返回,全部遍历完毕没问题就把它添加到前缀字符串里。

这样做效率比较差,有待改进。

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        unsigned minLen = 0xffffffff;
        unsigned i = 0;
        string res = "";
        vector<string>::iterator it;
           for (it = strs.begin();it != strs.end(); it++)    {
               cout << (*it).size();
               minLen = ((*it).size() < minLen) ? ((*it).size()) : minLen;
           }
           // cout << "minlen is " << minLen << endl;
           if ((!minLen) || (minLen == 0xffffffff))
               return "";
           // cout << "minlen is " << minLen << endl;
           while (i != minLen)    {
               char temp;
               bool flag = false;
               it = strs.begin();
               temp = (*it)[i];
               for (it = strs.begin(); it != strs.end(); it++)    {
                   if (temp != (*it)[i])    
                       return res;
               }
               res += temp;
               i ++;
           }
           return res;
    }
};

 

Longest common prefix | leetcode