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
#![allow(dead_code)]

// todo: there are some other solutions
pub fn longest_common_prefix(strs: Vec<String>) -> String {
    let mut common = String::new();
    if strs.len() == 0 {
        return common;
    } else if strs.len() == 1 {
        return strs[0].clone();
    }

    let mut k: usize = 0;
    loop {
        let cur_ch: char;
        match strs[0].chars().nth(k) {
            None => {
                return common;
            }
            Some(ch) => {
                cur_ch = ch;
            }
        };

        for i in 1..strs.len() {
            match strs[i].chars().nth(k) {
                Some(ch) if cur_ch == ch => {}
                _ => return common,
            }
        }

        common.push(cur_ch);
        k += 1;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test1() {
        let strs = vec![
            String::from("flower"),
            String::from("flow"),
            String::from("flight"),
        ];

        assert_eq!(longest_common_prefix(strs), String::from("fl"));
        assert_eq!(longest_common_prefix(vec![]), String::from(""));
        assert_eq!(
            longest_common_prefix(vec![String::from("flower")]),
            String::from("flower")
        );
    }
}