Fork me on GitHub

【LeetCode】14. 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 "";
        int prefix_len = strs[0].size();
        for (int i = 1; i < strs.size() ;++i){
            int j = 0;
            for (; j < prefix_len && strs[i][j] == strs[0][j]; ++j);
            prefix_len = j;
        }
        return strs[0].substr(0, prefix_len);
    }
};
posted @ 2015-08-24 19:23  __Neo  阅读(120)  评论(0编辑  收藏  举报