LeetCode(C++)刷题计划:14-最长公共前缀

14-最长公共前缀

@Author:CSU张扬
@Email:csuzhangyang@gmail.com or csuzhangyang@qq.com

Category Difficulty Pass rate Tags Companies
algorithms Easy 35.13% string yelp

1. 题目

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

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

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

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

说明: 所有输入只包含小写字母 a-z

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix/

2. 解法

2.1 解法一

  1. 从第一个位置开始,判断每个字符串该位置是否全部相等。
  2. 即:若 vector<string> 字符串为 str1, str2, str3
    • 我们比较 str1[0], str2[0], str3[0] 是否全部相等。
    • 若相等,比较 str1[1], str2[1], str3[1] 是否全部相等。
    • 依次下去比较,直至第一次不全部相等时结束。

执行用时: 8 ms, 在所有 cpp 提交中击败了71.92%的用户
内存消耗: 8.7 MB, 在所有 cpp 提交中击败了92.56%的用户

1. 将 vector<string> 视为二维数组:

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

2. 利用迭代器:

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        auto iter = strs.begin();
        string res = "";
        int maxSize = 0;
        for (auto i = 0; i < strs.size(); ++ i) {
            if ((*(iter + i)).size() > maxSize)
                maxSize = (*(iter + i)).size();
        }
        for (auto i = 0; i < maxSize; ++ i) {
            for (auto j = 0; j < strs.size() - 1; ++ j) {
                if ((*(iter + j))[i] != (*(iter + j + 1))[i]) {
                    return res;
                }
            }
            res += (*iter)[i];
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/MagicConch/p/12179156.html