-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy paths0014_longest_common_prefix.rs
More file actions
101 lines (88 loc) · 2.3 KB
/
s0014_longest_common_prefix.rs
File metadata and controls
101 lines (88 loc) · 2.3 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/**
* [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 {}
// problem: https://leetcode.com/problems/longest-common-prefix/
// discuss: https://leetcode.com/problems/longest-common-prefix/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
use std::str::Chars;
impl Solution {
pub fn longest_common_prefix(strs: Vec<String>) -> String {
let mut chars = strs.first().expect("Ok").clone();
strs.iter().map(|v| v.chars()).fold(chars, |prev, cur: Chars| {
let len = longest_len(&(prev.chars()), &cur);
let mut ch = String::from("");
if len == 0 {
return ch;
}
let mut iter_prev = prev.chars().into_iter();
let mut iter_cur = cur.into_iter();
for i in 0..=len-1 {
let p = iter_prev.next().unwrap();
if p == iter_cur.next().unwrap() {
ch.push(p);
} else {
break;
}
}
return ch;
})
}
}
pub fn longest_len<'a>(a: &'a Chars, b: &'a Chars) -> usize {
let a_len = a.clone().count();
let b_len = b.clone().count();
if a_len > b_len {
return b_len;
}
a_len
}
// 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![]), "");
}
}