From 551b7819cc8c5fce13cf14154b6660f175ae12b4 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 13 Apr 2023 08:13:07 +0200 Subject: [PATCH] =?UTF-8?q?problems(rs):=20add=20=E2=80=9C71.=20Simplify?= =?UTF-8?q?=20Path=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- problems/simplify-path.rs | 49 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 problems/simplify-path.rs diff --git a/problems/simplify-path.rs b/problems/simplify-path.rs new file mode 100644 index 0000000..f0c8fe1 --- /dev/null +++ b/problems/simplify-path.rs @@ -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() + ); + } +}