(LeetCode每日一刷05)最长公共前缀

题目描述:

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

示例:

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"

示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。

说明:

所有输入只包含小写字母 a-z 。

我提交的代码:

扫描二维码关注公众号,回复: 4112175 查看本文章
class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        int vec_size = strs.size();
        if(vec_size == 0)
        {
            return "";
        }
        string result = "";
        int i,j;
        int length = strs[0].size();
        char pre;
        
        if(length == 0)
        {
            return result;
        }
        
        char current;
        for (i = 0; i < length; ++i)
        {
            pre = strs[0][i];
            for (j = 0; j < vec_size; ++j)
            {
                if(strs[j].size() < i + 1)
                {
                    return result;
                }
                current = strs[j][i];
                if(pre != current)
                {
                    
                    return result;
                }
                
            }
            result = result + current;
        }
        return result;
        
    }
};

执行用时: 20 ms, 在Longest Common Prefix的C++提交中击败了9.59% 的用户

感想:快无语了。本想刷完所有简单题在回过来深入学习,还是决定刷完10题就每题深入学习吧!

猜你喜欢

转载自blog.csdn.net/songsong2017/article/details/84032974