Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 2abab0c

Browse files
author
Zhang Xiaodong
committed
solve 14
1 parent d50ee6a commit 2abab0c

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

src/solution/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@ mod s0009_palindrome_number;
99
mod s0011_container_with_most_water;
1010
mod s0012_integer_to_roman;
1111
mod s0013_roman_to_integer;
12+
mod s0014_longest_common_prefix;
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/**
2+
* [14] 最长公共前缀
3+
*
4+
* 编写一个函数来查找字符串数组中的最长公共前缀。
5+
* 如果不存在公共前缀,返回空字符串 ""。
6+
*
7+
* 示例 1:
8+
*
9+
* 输入:strs = ["flower","flow","flight"]
10+
* 输出:"fl"
11+
*
12+
* 示例 2:
13+
*
14+
* 输入:strs = ["dog","racecar","car"]
15+
* 输出:""
16+
* 解释:输入不存在公共前缀。
17+
*
18+
* 提示:
19+
*
20+
* 1 <= strs.length <= 200
21+
* 0 <= strs[i].length <= 200
22+
* strs[i] 仅由小写英文字母组成
23+
*
24+
*/
25+
pub struct Solution {}
26+
27+
// problem: https://leetcode.cn/problems/longest-common-prefix/
28+
// discuss: https://leetcode.cn/problems/longest-common-prefix/discuss/?currentPage=1&orderBy=most_votes&query=
29+
30+
// submission codes start here
31+
32+
impl Solution {
33+
pub fn longest_common_prefix(strs: Vec<String>) -> String {
34+
let mut its: Vec<Box<dyn Iterator<Item = &u8>>> = strs[1..]
35+
.iter()
36+
.map(|s| Box::new(s.as_bytes().iter()) as Box<dyn Iterator<Item = &u8>>)
37+
.collect();
38+
let mut end = 0;
39+
for c in strs[0].bytes() {
40+
for it in &mut its {
41+
let r = it.next();
42+
if r.is_none() || *r.unwrap() != c {
43+
return String::from(&strs[0].as_str()[..end]);
44+
}
45+
}
46+
end += 1;
47+
}
48+
strs[0].to_string()
49+
}
50+
}
51+
52+
// submission codes end
53+
54+
#[cfg(test)]
55+
mod tests {
56+
use super::*;
57+
58+
#[test]
59+
fn test_14() {
60+
Solution::longest_common_prefix(vec!["1".to_string()]);
61+
assert_eq!(
62+
Solution::longest_common_prefix(vec!["flower".to_string(), "flow".to_string(), "flight".to_string()]),
63+
"fl"
64+
);
65+
assert_eq!(
66+
Solution::longest_common_prefix(vec!["pig".to_string(), "sheep".to_string(), "flight".to_string()]),
67+
""
68+
);
69+
}
70+
}

0 commit comments

Comments
 (0)