[LeetCode] Longest Common Prefix

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

 1 class Solution {
 2 public:
 3     string longestCommonPrefix(vector<string>& strs) {
 4         if (strs.empty()) return "";
 5         
 6         for (int i = 0; i < strs[0].size(); ++i)
 7             for (int j = 1; j < strs.size(); ++j) {
 8                 if (strs[j][i] != strs[0][i]) return strs[0].substr(0,i); 
 9             }
10         
11         return strs[0];
12     }
13 };

 

posted @ 2015-04-16 19:41  vincently  阅读(147)  评论(0编辑  收藏  举报