14. Longest Common Prefix

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

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






原文地址:https://www.cnblogs.com/zhxshseu/p/340b6b560f218857a34c80e8841956e8.html