14. 最长公共前缀--LeetCode

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-common-prefix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

暴力出奇迹 打表过样例


class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        // 初始化答案
        string res="";
        // tag为1,意味着最长公共前缀已找到
        int tag=0;

        // 拿第一个串中的字符与后面的串中的字符比较 如果发现长度不一致或对应位置上的字符不同,说明最长公共前缀在上一次枚举中找到了
        for(int i=0;i<strs[0].size();i++){
            for(int j=1;j<strs.size();j++){
                if(i>strs[j].size() || strs[0][i] != strs[j][i]){
                    tag = !tag;
                    break;
                }
            }
            if(tag)break;
            res+=strs[0][i];
        }
        return res;
    }
};

posted @ 2022-08-11 20:44  0x4D5A  阅读(60)  评论(0)    收藏  举报