leetcode-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 "".

Example 1:

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

Example 2:

1
2
3
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.

分析

题意是有一堆字符串,求这些字符串中的最长公共前缀,可以将第一个字符串作为操作对象,比较第 n 个字符,只要出现一个字符串的第 n 个字符不等于第一个字符串的第 n 个字符,就返回第一个字符串的 0~n-1 子串。

解决方案1(Python)


1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""

length, count = len(strs[0]), len(strs)

for i in range(length):
nowCh = strs[0][i]
if any(i == len(strs[j]) or strs[j][i] != nowCh for j in range(1, count)):
return strs[0][:i]
return strs[0]

解决方案1(C++)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty()) {
return "";
}

for(int i = 0; i < strs[0].size(); i++) {
for(int j = 1; j < strs.size(); j++) {
if(strs[0][i] != strs[j][i]) {
return strs[0].substr(0, i);
}
}
}
return strs[0];
}
};

解决方案2(Rust)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
pub struct Solution {}

use std::str::Chars;
impl Solution {
pub fn longest_common_prefix(strs: Vec<String>) -> String {
let mut prefix = String::new();
let mut str_iters: Vec<Chars> = strs.iter().map(|s| {s.chars()}).collect();
let mut current_char: Option<char> = None;
if strs.len() < 1 {
return prefix
}

loop {
current_char.take().map(|ch| prefix.push(ch));
for iter in str_iters.iter_mut() {
let mut ch = iter.next();
if ch.is_none() {
return prefix
}
match current_char {
None => current_char = ch.take(),
Some(curr) => {
if curr != ch.unwrap() {
return prefix
}
}
}
}
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_leetcode_14() {
assert_eq!(Solution::longest_common_prefix(
vec![
"flower".to_string(),
"flow".to_string(),
"flight".to_string()
]), "fl");
assert_eq!(Solution::longest_common_prefix(
vec![
"dog".to_string(),
"racecar".to_string(),
"car".to_string()
]), "");
assert_eq!(Solution::longest_common_prefix(vec![]), "");
}
}

解决方案3(Golang)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
func longestCommonPrefix(strs []string) string {
strsCount := len(strs)
if strsCount == 0 {
return ""
}

var result = len(strs[0])

for nowStrIndex := 0; nowStrIndex < strsCount-1; nowStrIndex++ {
nowEnd := 0
nowStrLen := len(strs[nowStrIndex+1])
if nowStrLen > result {
nowStrLen = result
}
for i := 0; i < nowStrLen; i++ {
if strs[nowStrIndex][i] == strs[nowStrIndex+1][i] {
nowEnd++
} else {
break
}
}
if result >= nowEnd {
result = nowEnd
}
}
return strs[0][0: result]
}

题目来源