返回

[Leetcode] 14. Longest Common Prefix (C++)

题目描述

题目链接:14. Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

例子

例子 1

Input: ["flower","flow","flight"] Output: "fl"

例子 2

Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.

Note

All given inputs are in lowercase letters a-z.

解题思路

这道题要求的是所有给定字符串的最长公共子串,由于是要求所有字符串都要含有,所以只需要简单对所有字符串按顺序每一位进行比较即可。可以以第一个字符串含有的字符按顺序对之后所有字符串作比较,思路比较清晰,需要注意以下几个特殊例子不要越界:

  • 空向量的情况,这种情况没有第一个字符串;
  • 第后面字符串的长度比第一个字符串长的情况,需要加以判断
#include <vector>
#include <string>

class Solution {
public:
    std::string longestCommonPrefix(std::vector<std::string>& strs) {
        std::string prefix = "";
        if (strs.empty()) return prefix;
        for (int i = 0; i < strs[0].length(); i++) {
            char letter = strs[0][i];
            for (const std::string& str: strs) {
                if (i >= str.length() || str[i] != letter) return prefix;
            }
            prefix += letter;
        }
        return prefix;
    }
};
  • 时间复杂度: O(nm) - n 为字符串数量, m 为最短字符串长度
  • 空间复杂度: O(m) - 最长公共子串的长度
Built with Hugo
Theme Stack designed by Jimmy