码迷,mamicode.com
首页 > 其他好文 > 详细

Longest common prefix | leetcode

时间:2016-11-02 23:04:01      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:cout   find   color   write   字符串   迭代   end   signed   iterator   

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

标签:cout   find   color   write   字符串   迭代   end   signed   iterator   

原文地址:http://www.cnblogs.com/shawnye/p/6024561.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!