pegitan/leetcode/
problem_71.rs1use crate::Solution;
2
3impl Solution {
4 pub fn simplify_path<T>(path: T) -> String
5 where
6 T: Into<String>,
7 {
8 let mut stack: Vec<&str> = Vec::new();
9 let path = path.into();
10 path.split('/').for_each(|c: &str| {
11 if c == ".." {
12 if stack.len() > 0 {
13 stack.pop();
14 }
15 } else if c != "." && c.len() > 0 {
16 stack.push(c);
17 }
18 });
19 if stack.is_empty() {
20 String::from("/")
21 } else {
22 stack
23 .into_iter()
24 .filter(|c| !c.is_empty())
25 .fold(String::new(), |mut acc, x| {
26 acc.push_str("/");
27 acc.push_str(x);
28 acc
29 })
30 }
31 }
32}
33
34#[test]
35fn problem_71_test() {
36 assert_eq!(Solution::simplify_path("/home/"), "/home");
37 assert_eq!(Solution::simplify_path("/../"), "/");
38 assert_eq!(Solution::simplify_path("/home//foo/"), "/home/foo");
39 assert_eq!(Solution::simplify_path("/a/./b/../../c/"), "/c");
40 assert_eq!(Solution::simplify_path("/a/../../b/../c//.//"), "/c");
41 assert_eq!(Solution::simplify_path("/a//b////c/d//././/.."), "/a/b/c");
42}