class Solution {
public String simplifyPath(String path) {
String[] components = path.split("/");
Stack<String> st = new Stack<>();
for(String comp : components) {
if(comp.equals(".") || comp.equals("")) {
continue;
}
if(comp.equals("..")) {
if(!st.isEmpty()) {
st.pop();
}
} else {
st.push(comp);
}
}
StringBuilder sb = new StringBuilder();
for(String str1 : st) {// st will have stored everything
sb.append("/").append(str1);
}
return sb.length() == 0 ? "/" : sb.toString();
}
}
No comments:
Post a Comment