最长公共前缀

最长公共前缀

CategoryDifficultyLikesDislikes
algorithmsEasy (42.24%)2215-

Tags

string

Companies

yelp

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

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

示例 1:

1
2
输入:strs = ["flower","flow","flight"]
输出:"fl"

示例 2:

1
2
3
输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。

提示:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i]  仅由小写英文字母组成

Discussion | Solution

解法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// @lc code=start
impl Solution {
    /// ## 解题思路
    /// - 依次比较其他字符串各位字符和第一个字符串字符,记录相同的前缀;
    pub fn longest_common_prefix(strs: Vec<String>) -> String {
        match strs.is_empty() {
            true => "".to_string(),
            _ => strs.iter().skip(1).fold(strs[0].clone(), |acc, s| {
                acc.chars()
                    .zip(s.chars())
                    .take_while(|(c1, c2)| c1 == c2)
                    .map(|(c1, _)| c1)
                    .collect()
            }),
        }
    }
}
// @lc code=end

struct Solution;
  • python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
    def longestCommonPrefix(self, strs):
        size = len(strs)
        if size == 0:
            return ""
        if size == 1:
            return strs[0]
        min_len = len(min(strs, key=len))
        for i in range(min_len):
            c = strs[0][i]
            for j in range(1, size):
                s = strs[j]
                if c != s[i]:
                    return s[:i]
        if min_len < 1:
            return ""
        return strs[0][:min_len]
  • cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
    /**
     * ## 解题思路
     * * 双层遍历
     * * 遍历时,依次将各个字符串字符和strs[0]的字符对比
     */
    string longestCommonPrefix(vector<string>& strs) {
        string res;
        bool out = false;
        for(int i=0; !out; i++) {
            for(string& s: strs) {
                if (i>=s.length() || s[i] != strs[0][i]) {
                    out=true;
                    break;
                }
            }
            if (!out) {
                res += strs[0][i];
            }
        }
        return res;
    }
};
updatedupdated2024-05-152024-05-15