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

题意:找出所有字符串共同的最长前缀;

思路:因为是共同前缀,所以,求得第一个字符串和第二个字符的共同前缀以后,以这个前缀和后面的字符串去比较,更新前缀。代码如下:

 1 class Solution {
 2 public:
 3     string longestCommonPrefix(vector<string> &strs) 
 4     {
 5         if(strs.empty())    return "";
 6         string res="";
 7         res+=strs[0];
 8         for(int i=1;i<strs.size();++i)
 9         {
10             int j=0;
11             for( ;j<res.size()&&j<strs[i];++j)
12             {
13                 if(res[j] !=strs[i][j])
14                     break;
15             }
16             res=res.substr(0,j);
17         }
18         return res;
19     }
20 };

 

相关文章:

  • 2022-01-26
  • 2021-07-09
  • 2021-06-13
  • 2021-12-23
  • 2021-10-02
  • 2022-12-23
  • 2022-12-23
  • 2021-12-22
猜你喜欢
  • 2021-06-28
  • 2021-09-14
  • 2021-04-19
  • 2021-12-14
  • 2021-05-06
  • 2021-06-12
相关资源
相似解决方案