首页 > 其他 > 详细

LeetCode #14 简单题(多字符串的最长公共前缀)

时间:2019-10-11 00:33:23      阅读:134      评论:0      收藏:0      [点我收藏+]

题目: 求多个字符串的最长公共前缀。

题解: 都跟第一个字符串比一下就行了,注意字符串长度边界。

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        int n = (int)strs.size();
        if (n == 0)return "";
        if (n == 1)return strs[0];

        int index = 0;
        while(true){
            bool findIndex = false;
            for (int i = 1; i < n; ++i){
                if (index >= strs[i].size() || 
                    index >= strs[0].size() || 
                    strs[i][index] != strs[0][index]){
                    findIndex = true;
                    break;
                }
            }
            if (findIndex) break;
            index ++;
        }
        return strs[0].substr(0, index);
    }
};

 

LeetCode #14 简单题(多字符串的最长公共前缀)

原文:https://www.cnblogs.com/error408/p/11651183.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!