Chinaunix首页 | 论坛 | 博客
  • 博客访问: 255920
  • 博文数量: 170
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1709
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-06 18:01
文章分类

全部博文(170)

文章存档

2016年(11)

2015年(130)

2014年(29)

分类: Java

2015-09-10 18:26:21

/Simplify Path Total Accepted: 35464 Total Submissions: 176460 My Submissions Question Solution 
//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.
import java.util.Stack;


public class SimplifyPath {


public static void main(String[] args) {
// TODO Auto-generated method stub
 
}
public String simplifyPath(String path) {
if(path.length()==0||path.charAt(0)!='/')
return "";
Stack<String> vec=new Stack<String>() ;  
       
       String curpath=path.substring(1);
       int firstindex=0;
       while(firstindex!=-1)  
       {  
           firstindex=curpath.indexOf("/");
           String sub="";
           if(firstindex==-1){
            sub = curpath.substring(0,curpath.length()); 
           curpath=curpath.substring(firstindex+1);
           }else{
            sub = curpath.substring(0,firstindex); 
           curpath=curpath.substring(firstindex+1);
           }
          
           if(sub.length()>0){  
               if(sub .equals("..") ){  
                   if(!vec.isEmpty()) vec.pop();  
               }  
               else if(!sub .equals("."))  
                   vec.push(sub);  
           }  
          
       }  
    
       if(vec.isEmpty()){
        return "/";
       }
       String res = "";
       
       while(!vec.isEmpty()){
        res = "/"+vec.pop() + res;
       }
       return res;  
   }
}

阅读(473) | 评论(0) | 转发(0) |
0

上一篇:ClimbStairs

下一篇:Edit Distance

给主人留下些什么吧!~~