rustgym/leetcode/
_71_simplify_path.rs

1struct Solution;
2
3impl Solution {
4    fn simplify_path(path: String) -> String {
5        let mut stack: Vec<&str> = vec![];
6        let mut res = "".to_string();
7        for s in path.split_terminator('/') {
8            match s {
9                ".." => {
10                    stack.pop();
11                }
12                "" | "." => {
13                    continue;
14                }
15                _ => {
16                    stack.push(s);
17                }
18            }
19        }
20        for s in stack {
21            res += "/";
22            res += s;
23        }
24        if res.is_empty() {
25            res += "/";
26        }
27        res
28    }
29}
30
31#[test]
32fn test() {
33    let path = "/home/".to_string();
34    let res = "/home".to_string();
35    assert_eq!(Solution::simplify_path(path), res);
36    let path = "/../".to_string();
37    let res = "/".to_string();
38    assert_eq!(Solution::simplify_path(path), res);
39    let path = "/home//foo/".to_string();
40    let res = "/home/foo".to_string();
41    assert_eq!(Solution::simplify_path(path), res);
42    let path = "/a/./b/../../c/".to_string();
43    let res = "/c".to_string();
44    assert_eq!(Solution::simplify_path(path), res);
45    let path = "/a/../../b/../c//.//".to_string();
46    let res = "/c".to_string();
47    assert_eq!(Solution::simplify_path(path), res);
48    let path = "/a//b////c/d//././/..".to_string();
49    let res = "/a/b/c".to_string();
50    assert_eq!(Solution::simplify_path(path), res);
51}