14. 最长公共前缀

  1. 题目链接

  2. 解题思路:用第一个字符串的每个字符,逐个比较其他字符串,注意别越界就行

  3. 代码

    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            string ans = "";
            int len = strs[0].length();
            int n = strs.size();
            for (int i = 0; i < len; ++i) {   // 遍历第一个字符串的每个字符
                char ch = strs[0][i];
                bool flag = true;
                for (int j = 1; j < n; ++j) {   //  对比其他的字符串
                    if (strs[j].length() <= i || strs[j][i] != ch) {   // 注意不要越界
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    ans.push_back(ch);
                } else {
                    break;
                }
            }
            return ans;
        }
    };
    
posted @ 2024-12-18 08:57  ouyangxx  阅读(9)  评论(0)    收藏  举报