Longest Common Prefix

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

 

Analyse: 找一些序列的最长前缀子序列。

 

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

 

你可能感兴趣的:(long)