Leetcode
This file contains 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
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". | |
public class Solution { | |
public String simplifyPath(String path) { | |
StringBuilder result=new StringBuilder(); | |
if (path==null ||path.length()==0){ | |
return result.toString(); | |
} | |
String[] strs=path.split("/"); | |
Stack<String> stack=new Stack<String>(); | |
for (String s: strs){ | |
if (s.length()==0 ||s.equals(".")){ | |
} | |
else if (s.equals("..")){ | |
if (!stack.isEmpty()){ | |
stack.pop(); | |
} | |
} | |
else{ | |
stack.push(s); | |
} | |
} | |
if (stack.isEmpty()){ | |
result.append('/'); | |
} | |
else{ | |
while (!stack.isEmpty()){ | |
result.insert(0, stack.pop()); | |
result.insert(0, '/'); | |
} | |
} | |
return result.toString(); | |
} | |
} |
No comments:
Post a Comment