题目
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: ""
解题思路
是一道简单题,基本思路就是先找到最小需要比较的位数,确定循环边界,然后依次比对就可以了
代码
fn longest_common_prefix(strs: Vec<String>) -> String {
if strs.len() == 0 {
return String::from("");
}
if strs.len() == 1 {
return strs[0].to_string();
}
let min_len = strs.iter().map(|s| s.len()).min().unwrap();
for i in 0..min_len {
let c = strs[0].chars().nth(i).unwrap();
for s in &strs {
if s.chars().nth(i).unwrap() != c {
return s[0..i].to_string();
}
}
}
return strs[0][..min_len].to_string();
}
#[test]
fn test_logest_common_prefix() {
let demo = vec![String::from("flower"), String::from("flow"), String::from("flight")];
assert_eq!(longest_common_prefix(demo), "fl");
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。