首页 > 代码库 > Simplify Path
Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
click to show corner cases.
Corner Cases:
- Did you consider the case where path =
"/../"
?
In this case, you should return"/"
. - Another corner case is the path might contain multiple slashes
‘/‘
together, such as"/home//foo/"
.
In this case, you should ignore redundant slashes and return"/home/foo"
.
it takes me a lot of time...
1 class Solution { 2 public: 3 string simplifyPath(string path) { 4 vector<string> s; 5 string name; 6 const char *p = path.c_str(); 7 while (*p != ‘\0‘) 8 { 9 while (*p == ‘/‘) //去除多余的/10 p++;11 while (*p != ‘/‘ && *p !=‘\0‘) //分段,用name储存12 {13 name.push_back(*p++);14 }15 if (name[0] == ‘\0‘) //是否是结尾,结尾则不处理16 ;17 else if (name.compare("..") == 0) //判断是否有上一级目录,有则返回上一级目录18 {19 if (s.size() > 0)20 s.erase(s.end());21 }22 else if (name.compare(".") != 0) //当前目录.不用处理,否则加入到vector中23 {24 s.push_back(name);25 }26 name.erase(0);27 }28 string ret;29 if (s.size() == 0) //特殊情况/30 return "/";31 vector<string>::iterator it;32 for(it=s.begin(); it!=s.end(); it++){33 ret += "/";34 ret += *it;35 }36 return ret;37 }38 };
Simplify Path
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。