坚持天天一道题,刷题学习Rust.git
https://leetcode-cn.com/problems/simplify-path/github
以 Unix 风格给出一个文件的绝对路径,你须要简化它。或者换句话说,将其转换为规范路径。学习
在 Unix 风格的文件系统中,一个点(.)表示当前目录自己;此外,两个点 (..) 表示将目录切换到上一级(指向父目录);二者均可以是复杂相对路径的组成部分。更多信息请参阅:Linux / Unix中的绝对路径 vs 相对路径code
请注意,返回的规范路径必须始终以斜杠 / 开头,而且两个目录名之间必须只有一个斜杠 /。最后一个目录名(若是存在)不能以 / 结尾。此外,规范路径必须是表示绝对路径的最短字符串。leetcode
示例 1:字符串
输入:"/home/"
输出:"/home"
解释:注意,最后一个目录名后面没有斜杠。
示例 2:get
输入:"/../"
输出:"/"
解释:从根目录向上一级是不可行的,由于根是你能够到达的最高级。
示例 3:string
输入:"/home//foo/"
输出:"/home/foo"
解释:在规范路径中,多个连续斜杠须要用一个斜杠替换。
示例 4:it
输入:"/a/./b/../../c/"
输出:"/c"
示例 5:io
输入:"/a/../../b/../c//.//"
输出:"/c"
示例 6:
输入:"/a//b////c/d//././/.."
输出:"/a/b/c"
思路:
struct Solution {} impl Solution { pub fn simplify_path(path: String) -> String { let mut st = Vec::new(); let ss: Vec<_> = path.split("/").collect(); for s in path.split("/") { // println!("s={}", s); if s.len() == 0 { continue; } else if s == ".." { st.pop(); } else if s == "." { continue; } else { st.push(s); } } let mut s = String::new(); for t in st { s += "/"; s += t; } if s.len() == 0 { s += "/" } s } } mod test { use super::*; #[test] fn test_path() { assert_eq!( "/home/foo", Solution::simplify_path(String::from("/home//foo/")) ); assert_eq!("/home", Solution::simplify_path(String::from("/home"))); assert_eq!("/", Solution::simplify_path(String::from("/../"))); assert_eq!( "/c", Solution::simplify_path(String::from("/a/./b/../../c/")) ); assert_eq!( "/a/b/c", Solution::simplify_path(String::from("/a//b////c/d//././/..")) ); } }
太简单了,有凑数之嫌,下次应该找一些有价值的来作
欢迎关注个人github,本项目文章全部代码均可以找到.