Longest Common Prefix

2017-12-20  本文已影响0人  无云清晨

字符串数组的公共前缀

 string longestCommonPrefix(vector<string>& strs)
 {

   bool isMatch = true;
   string w;
   string word;
   if (strs.size()<=0) return word;
   for(int i = 1; i <= strs[0].size(); i++)
   {
     w = strs[0].substr(0, i);
     for(int j = 1; j < strs.size(); j++)
     {
       if(strs[j].size() < i || w != strs[j].substr(0,i))
       {
          isMatch = false;
          break;
       }
     }

     if(!isMatch)
     {
       return word;
     }

     word = w;
   }

   return word;
 }
上一篇下一篇

猜你喜欢

热点阅读