https://leetcode.com/problems/longest-common-prefix/

原题:

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

思路:

简单,直接遍历查找即可。

AC代码:

 1 class Solution {
 2 public:
 3     string longestCommonPrefix(vector<string>& strs) {
 4         int n=strs.size();
 5         if (n==1)
 6             return strs[0];
 7         if (n==0)
 8             return "";
 9         int k=strs[0].size();
10         bool flag=true;
11         string res="";
12         for(int i=0;i<n;i++)
13             k=(k<strs[i].size())? k:strs[i].size();
14         for(int t=0;t<k;t++){
15             for(int i=0;i<n;i++){
16                 if(strs[i][t]!=strs[0][t]){
17                     flag=false;
18                     break;
19                 }
20             }
21             if (flag==true)
22                 res.push_back(strs[0][t]);
23             else 
24                 break;
25         }
26         return res;
27     }
28 };