The idea is to divide by blocks and process each block like "/.."; a stack is defined to store temporary results, which is a String sequence, and some pop and push operations are involved in the logic.
Some edge conditions need to be careful and clarified.
public class Solution {
public String simplifyPath(String path) {
if(path == null || (path.length() == 1 && path.charAt(0) != '/')){
return null;
}
Stack<String> process = new Stack<String>();
boolean oneBlock = false;
int index = 1;
int startIndex = 0;
while(index < path.length()){
if(path.charAt(index) == '/' || index == path.length() - 1){
oneBlock = true;
}
if(oneBlock){
int base = 0;
if(index == path.length() - 1 && path.charAt(index) != '/'){
base = 1;
}
String cur = path.substring(startIndex, index + base);
startIndex = index;
if(cur.equalsIgnoreCase("/..") && !process.isEmpty()){
process.pop();
}
if(!cur.equalsIgnoreCase("/..") && !cur.equalsIgnoreCase("/.") && !cur.equalsIgnoreCase("/")){
process.push(cur);
}
oneBlock = false;
}
index++;
}
if(process.isEmpty()){
return "/";
}
StringBuilder result = new StringBuilder();
while(!process.isEmpty()){
result.insert(0, process.pop());
}
return result.toString();
}
}
没有评论:
发表评论