美文网首页工作生活
14. Longest Common Prefix 最长公共前缀

14. Longest Common Prefix 最长公共前缀

作者: xingzai | 来源:发表于2019-07-04 17:34 被阅读0次

    题目链接
    tag:

    • Easy;

    question:
      Write a function to find the longest common prefix string amongst an array of strings.
    If there is no common prefix, return an empty string "".

    Example 1:

    Input: ["flower","flow","flight"]
    Output: "fl"

    Example 2:

    Input: ["dog","racecar","car"]
    Output: ""
    Explanation: There is no common prefix among the input strings.

    Note: All given inputs are in lowercase letters a-z.

    思路:
      本题比较简单,只需要遍历第一个字符串的字符,如果当前字符的index大于后面的字符串长度,或者跟后面每个字符串的同位置字符不相同,则直接返回即可。代码如下:

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

    相关文章

      网友评论

        本文标题:14. Longest Common Prefix 最长公共前缀

        本文链接:https://www.haomeiwen.com/subject/digrhctx.html