Created
June 23, 2013 03:59
-
-
Save luoxiaoxun/5843748 to your computer and use it in GitHub Desktop.
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,…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| C++: | |
| class Solution { | |
| public: | |
| string simplifyPath(string path) { | |
| // Start typing your C/C++ solution below | |
| // DO NOT write int main() function | |
| stack<string> result; | |
| string cur; | |
| for(int i=0;i<path.length();i++){ | |
| if(path[i]=='/'){ | |
| if(cur==".."){ | |
| if(!result.empty()) | |
| result.pop(); | |
| } | |
| else if(cur!="."&&cur!="") result.push(cur); | |
| cur=""; | |
| }else cur +=path[i]; | |
| } | |
| if(cur==".."){ | |
| if(!result.empty()) | |
| result.pop(); | |
| } | |
| else if(cur!="."&&cur!="") result.push(cur); | |
| if(result.empty()) return "/"; | |
| string res; | |
| while(!result.empty()){ | |
| res ="/"+result.top()+res; | |
| result.pop(); | |
| } | |
| return res; | |
| } | |
| }; | |
| Java: | |
| public class Solution { | |
| public String simplifyPath(String path) { | |
| // Start typing your Java solution below | |
| // DO NOT write main() function | |
| Stack<String> result=new Stack<String>(); | |
| String cur=""; | |
| for(int i=0;i<path.length();i++){ | |
| if(path.charAt(i)=='/'){ | |
| if(cur.equals("..")){ | |
| if(!result.empty()) | |
| result.pop(); | |
| }else if(!cur.equals(".")&&!cur.equals("")) result.push(cur); | |
| cur=""; | |
| }else cur +=path.charAt(i); | |
| } | |
| if(cur.equals("..")){ | |
| if(!result.empty()) | |
| result.pop(); | |
| }else if(!cur.equals(".")&&!cur.equals("")) result.push(cur); | |
| if(result.empty()) return "/"; | |
| String res=""; | |
| while(!result.empty()){ | |
| res ="/"+result.peek()+res; | |
| result.pop(); | |
| } | |
| return res; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment