博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Simplify Path
阅读量:6844 次
发布时间:2019-06-26

本文共 1665 字,大约阅读时间需要 5 分钟。

Given an absolute path for a file (Unix-style), simplify it.

For example,

path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

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".

思路:

用一个栈来实现,对特殊情况进行判断

代码:

1     string simplifyPath(string path) { 2         // IMPORTANT: Please reset any member data you declared, as 3         // the same Solution instance will be reused for each test case. 4         stack
Stack; 5 while(true){ 6 if(path == "/") 7 break; 8 int index = path.find('/', 1); 9 string tmp;10 if(index == -1){11 tmp = path.substr(1);12 path = "/";13 }14 else{15 tmp = path.substr(1, index-1);16 path = path.substr(index);17 }18 if(tmp == "")19 continue;20 else if(tmp == ".."){21 if(!Stack.empty())22 Stack.pop();23 else24 continue;25 }26 else if(tmp != ".") 27 Stack.push(tmp);28 }29 string result = "";30 if(Stack.empty())31 return "/";32 while(!Stack.empty()){33 result = "/" + Stack.top() + result;34 Stack.pop();35 }36 return result;37 }

 

转载于:https://www.cnblogs.com/waruzhi/p/3442496.html

你可能感兴趣的文章