经典指数          
原因
898
浏览数
0
收藏数
 

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".

     举报   纠错  
 
切换
1 个答案
import java.util.Stack; public class Solution { public String simplifyPath(String path) { if(path==null||path.length()<=1) return path; Stack stack = new Stack(); for(int i = 0;i1&&stack.peek()!='/') stack.pop(); i++; }else if(i+2==path.length()&&path.substring(i, i+2).equals("..")){ //判断/.. 返回上一个目录 stack.pop();//弹出当前目录 while(stack.size()>1&&stack.peek()!='/') stack.pop(); i++; }else{ while(i!=path.length()&&path.charAt(i)!='/') stack.add(path.charAt(i++)); if(i!=path.length()) i--; } } else stack.add(path.charAt(i)); } if(stack.isEmpty()) stack.add('/'); else if(stack.peek()=='/'&&stack.size()!=1) stack.pop(); char[] result = new char[stack.size()]; for(int i = result.length-1;i>=0;i--){ result[i] = stack.pop(); } return new String(result); } }
 
切换
撰写答案
扫描后移动端查看本题