LeetCode : Longest Common Prefix

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

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if (strs.empty()) return "";
        for (int pos = 0; pos < strs[0].length(); pos++)
            for (int i = 1; i < strs.size(); i++)
                if (pos >= strs[i].length() || strs[i][pos] != strs[0][pos])
                    return strs[0].substr(0, pos);
        return strs[0];
    }
};

posted on 2017-04-23 20:11  gechen  阅读(64)  评论(0编辑  收藏  举报

导航