-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0071_simplify_path.rs
More file actions
75 lines (71 loc) · 2.12 KB
/
s0071_simplify_path.rs
File metadata and controls
75 lines (71 loc) · 2.12 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#![allow(unused)]
pub struct Solution {}
impl Solution {
pub fn simplify_path(mut path: String) -> String {
format!(
"/{}",
path.split("/")
.filter(|x| *x != "" && *x != ".")
.fold(vec![], |mut s, section| {
match section {
".." => match s.last() {
Some(&"..") | None => { s.push("..") }
_ => { s.pop(); }
}
x => match s.last() {
Some(&"..") => { s.pop(); s.push(x); }
_ => { s.push(x) }
}
};
s
})
.into_iter()
.skip_while(|x| *x == "..")
.collect::<Vec<&str>>()
.join("/")
)
}
pub fn simplify_path_other(path: String) -> String {
let mut stack = vec![];
for part in path.split("/") {
if part == ".." {
stack.pop();
} else if part == "." {
continue;
} else {
if !part.is_empty() {
stack.push(part);
}
}
}
format!("/{}", stack.join("/"))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_71() {
assert_eq!(
Solution::simplify_path("/home/".to_string()),
"/home".to_string()
);
assert_eq!(Solution::simplify_path("/../".to_string()), "/".to_string());
assert_eq!(
Solution::simplify_path("/home//foo/".to_string()),
"/home/foo".to_string()
);
assert_eq!(
Solution::simplify_path("/a/./b/../../c/".to_string()),
"/c".to_string()
);
assert_eq!(
Solution::simplify_path("/a/../../b/../c//.//".to_string()),
"/c".to_string()
);
assert_eq!(
Solution::simplify_path("/a//b////c/d//././/..".to_string()),
"/a/b/c".to_string()
);
}
}