Simplify Path
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".
Solution
public class Solution {
public String simplifyPath(String path) {
int prev = -1;
List<String> components = new ArrayList<>();
for (int i = 0; i < path.length(); i++) {
if (path.charAt(i) == '/') {
if (prev >= 0) {
components.add(path.substring(prev + 1, i));
}
prev = i;
}
}
if (prev >= 0) {
components.add(path.substring(prev+1));
}
List<String> filter = new ArrayList<>();
for (String item : components) {
if (item.equals(".")) {
continue;
}
if (item.equals("..")) {
if (!filter.isEmpty()) {
filter.remove(filter.size() - 1);
}
} else if (item.length() > 0){
filter.add(item);
}
}
StringBuffer sb = new StringBuffer();
for(String item:filter) {
sb.append("/");
sb.append(item);
}
if (sb.length() == 0) {
return "/";
}
return sb.toString();
}
}