14. Longest Common Prefix

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

 

输出几个字符串的最长公共前缀

 

C++(6ms):

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

 

posted @ 2017-10-20 09:50  __Meng  阅读(135)  评论(0编辑  收藏  举报