[LintCode] 最长公共前缀

 1 class Solution {
 2 public:    
 3     /**
 4      * @param strs: A list of strings
 5      * @return: The longest common prefix
 6      */
 7     string longestCommonPrefix(vector<string> &strs) {
 8         // write your code here
 9         string lcp = "";
10         if (strs.empty()) return lcp;
11         for (int i = 0; i < (int)strs[0].length(); i++) {
12             int pos = lcp.length();
13             char letter = strs[0][pos];
14             for (int j = 1; j < (int)strs.size(); j++)
15                 if (strs[j].length() == pos || strs[j][pos] != letter)
16                     return lcp;
17             lcp += letter;
18         }
19         return lcp;
20     }
21 };

 

posted @ 2015-06-29 15:25  jianchao-li  阅读(183)  评论(0编辑  收藏  举报