导航

LeetCode 14. Longest Common Prefix

Posted on 2016-09-18 23:39  CSU蛋李  阅读(107)  评论(0编辑  收藏  举报

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

让我们在一个字符串中找出所有字符串的共同前缀

 

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string result = "";
        if (!strs.size())return result;
        result = strs[0];
        for (auto &e : strs)
        {
            if (e.size() < result.size())
                result = e;
        }
        for (auto &e : strs)
        {
            int i = 0;
            for (;i < result.size();++i)
            {
                if (e[i] != result[i])break;
            }
            result=result.substr(0, i);
        }
        return result;
    }
};