71. Simplify Path
Deque Stack, String[] strings = path.split("/");
class Solution {
public String simplifyPath(String path) {
// use Deque as Stack, LinkedList implementation
// method: deque.size()
Deque<String> memo = new LinkedList<>();
// get all substrings in between "/"
// method: string.split(string), may get empty string
String[] strings = path.split("/");
for(String str : strings){
// compare sting: string.equals(string);
if(str.equals("..") && memo.size()>0){
// deque.pop() retrive and remove the first element of deque
memo.pop();
}else if(!str.equals("..") && !str.equals(".") && !str.equals("")){
memo.push(str);
}
}
StringBuilder result = new StringBuilder();
while(memo.size()>0){
result.append('/'+memo.removeLast());
}
return result.length()>0? result.toString() : "/";
}
}
Last updated
Was this helpful?