forked from aylei/leetcode-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathn0014_longest_common_prefix.rs
76 lines (70 loc) · 2.02 KB
/
n0014_longest_common_prefix.rs
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* [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:
*
*
* Input: ["flower","flow","flight"]
* Output: "fl"
*
*
* Example 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.
*
*/
pub struct Solution {}
// submission codes start here
use std::str::Chars;
impl Solution {
pub fn longest_common_prefix(strs: Vec<String>) -> String {
let mut prefix = String::new();
let mut iters: Vec<Chars> = strs.iter().map(|s| {s.chars()}).collect();
let mut curr_char: Option<char> = None;
if strs.len() < 1 { return prefix }
loop {
curr_char.take().map(|ch| prefix.push(ch));
for iter in iters.iter_mut() {
let mut ch = iter.next();
if ch.is_none() {
return prefix
}
match curr_char {
None => curr_char = ch.take(),
Some(curr) => {
if curr != ch.unwrap() {
return prefix
}
}
}
}
}
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_14() {
assert_eq!(Solution::longest_common_prefix(vec!["".to_string(),
"racecar".to_string(),
"car".to_string()]), "");
assert_eq!(Solution::longest_common_prefix(vec!["flower".to_string(),
"flow".to_string(),
"flight".to_string()]), "fl");
assert_eq!(Solution::longest_common_prefix(vec![]), "");
}
}