首页 > 其他 > 详细

LeetCode_Stack_Simplify Path

时间:2015-07-01 10:10:02      阅读:116      评论:0      收藏:0      [点我收藏+]

71. Simplify Path

技术分享


1. 问题描述:

输入一个目录String,要求简化目录并返回。

2. 解决思路:

题目需要仔细阅读,要求简化路径。所以有几种情况,需要分情况讨论:

  1. /./ 不做任何目录操作
  2. /../ 跳到上一级目录
  3. // 不做任何目录操作

这里我们使用stack存储目录名,然后遇到操作符号 ‘/./’,’/../’,’//’,做相应操作,具体看代码。

3. java代码:

public class Solution {
    public String simplifyPath(String path) {

        if(path==null || path.length()==0)
            return path;

        String[] pathList = path.split("/");
        String result = "";
        Stack<String> stack = new Stack<String>();

        for(int i=0;i<pathList.length;i++){
            if(pathList[i].equals(".")|| pathList[i].length()==0) {
                continue;
            } else if(pathList[i].equals("..")) {
                if(!stack.empty()){
                    stack.pop();
                }
            } else { 
                stack.push(pathList[i]); 
            }
        }

        for(int j=0;j<stack.size();j++){
            result +="/"+stack.get(j);
        }
        return result=="" ? "/" : result; 
    }
}

4. 算法评估:

技术分享


希望多多指正交流!

版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode_Stack_Simplify Path

原文:http://blog.csdn.net/gldemo/article/details/46703805

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!