[Leetcode] longest common prefix 最长共同前缀

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 };

 

posted @ 2017-07-18 15:22  王大咩的图书馆  阅读(198)  评论(0编辑  收藏  举报