problems(rs): add “71. Simplify Path”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
5a62aba9c1
commit
551b7819cc
1 changed files with 49 additions and 0 deletions
49
problems/simplify-path.rs
Normal file
49
problems/simplify-path.rs
Normal file
|
@ -0,0 +1,49 @@
|
|||
struct Solution {}
|
||||
impl Solution {
|
||||
pub fn simplify_path(path: String) -> String {
|
||||
let mut simplified_path = Vec::<&str>::new();
|
||||
|
||||
path.split('/').for_each(|seg| {
|
||||
if seg.is_empty() || seg == "." {
|
||||
return;
|
||||
}
|
||||
|
||||
if seg == ".." {
|
||||
simplified_path.pop();
|
||||
return;
|
||||
}
|
||||
|
||||
simplified_path.push(seg);
|
||||
});
|
||||
|
||||
"/".to_owned() + &simplified_path.join("/")
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn one_directory() {
|
||||
assert_eq!(
|
||||
Solution::simplify_path("/home/".to_owned()),
|
||||
"/home".to_owned()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn just_root() {
|
||||
assert_eq!(Solution::simplify_path("/../".to_owned()), "/".to_owned());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consecutive_slashes() {
|
||||
assert_eq!(
|
||||
Solution::simplify_path("/home//foo/".to_owned()),
|
||||
"/home/foo".to_owned()
|
||||
);
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue