LeetCode OJ:Longest Common Prefix(最长公共前缀)

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

求很多string的公共前缀,用个两重循环就可以,代码如下:

 1 class Solution {
 2 public:
 3     string longestCommonPrefix(vector<string>& strs) {
 4         string prefix;
 5         if(strs.size() == 0 || strs[0].size() == 0)
 6             return "";
 7         int start = 0;
 8         bool endLoop = false;
 9         char cmp = strs[0][0];
10         while(true && !endLoop){
11             cout << cmp << endl;
12             for(int i = 0; i < strs.size(); ++i){
13                 if(start >= strs[i].size() || cmp != strs[i][start]){
14                     endLoop = true;
15                     break;
16                 }
17             }    
18             if(!endLoop){
19                 start++;
20                 if(start < strs[0].size())
21                     cmp = strs[0][start];
22             }
23 
24         }
25         return strs[0].substr(0, start - 1);
26     }
27 };

 

posted @ 2015-11-04 19:23  eversliver  阅读(223)  评论(0编辑  收藏  举报