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: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

 

Constraints:

  • 0 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lower-case English letters.

Rust Solution

struct Solution;

impl Solution {
    fn longest_common_prefix(strs: Vec<String>) -> String {
        if strs.is_empty() {
            return String::from("");
        }
        let ss: Vec<Vec<char>> = strs.iter().map(|s| s.chars().collect()).collect();
        let n = ss.iter().map(|s| s.len()).min().unwrap();
        let mut prefix: Vec<char> = vec![];
        for i in 0..n {
            let c = ss[0][i];
            if ss.iter().all(|s| s[i] == c) {
                prefix.push(c);
            } else {
                break;
            }
        }
        prefix.iter().collect()
    }
}

#[test]
fn test() {
    let ss: Vec<String> = vec_string!["flower", "flow", "flight"];
    assert_eq!(Solution::longest_common_prefix(ss), String::from("fl"));
}

Having problems with this solution? Click here to submit an issue on github.