Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c" path = "/../", => "/" path = "/home//foo/", => "/home/foo"
Java Solution
public String simplifyPath(String path) { Stack<String> stack = new Stack<String>(); //stack.push(path.substring(0,1)); while(path.length()> 0 && path.charAt(path.length()-1) =='/'){ path = path.substring(0, path.length()-1); } int start = 0; for(int i=1; i<path.length(); i++){ if(path.charAt(i) == '/'){ stack.push(path.substring(start, i)); start = i; }else if(i==path.length()-1){ stack.push(path.substring(start)); } } LinkedList<String> result = new LinkedList<String>(); int back = 0; while(!stack.isEmpty()){ String top = stack.pop(); if(top.equals("/.") || top.equals("/")){ //nothing }else if(top.equals("/..")){ back++; }else{ if(back > 0){ back--; }else{ result.push(top); } } } //if empty, return "/" if(result.isEmpty()){ return "/"; } StringBuilder sb = new StringBuilder(); while(!result.isEmpty()){ String s = result.pop(); sb.append(s); } return sb.toString(); } |
public static void main(String []args){
String f=”/home/”;
String[] s=f.split(“/”);
for(String ss:s){
System.out.println(“”+ss);
}
Stack q= new Stack();
for(String ss:s){
if(ss.equals(“”)) continue;
if(ss.equals(“..”) && !q.isEmpty() ){
q.pop();
}else if(ss.equals(“..”) && q.isEmpty() ){
continue;
}else if(ss.equals(“.”)) continue;
else{
q.push(ss);
}
}
System.out.println(q);
Actually, I believe there is an error in this solution for the input case of “./../home” it will return “/home” instead of “home” or “./home”. I haven’t thought about the fix though 😉
But “..” should not be ignored…
You have to go back one level.
“./a/b/c/../../d” == “./a/d”
This is handled by item.contains(“.”) as “..” contains a “.” inside of it. Therefore it will be ignored.
what about “..” ?
Here is a solution that is much more efficient that I thought of in a couple of minutes.
public static String simplifyPath(String path){
String[] array = path.split(“/”);
StringBuilder builder = new StringBuilder();
for(String item : array){
if(!item.contains(“.”) && !item.isEmpty()){
builder.append(“/”);
builder.append(item);
}
}
return builder.toString();
}