码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode_Stack_Simplify Path

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

标签:leetcode   算法   java   stack      

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

标签:leetcode   算法   java   stack      

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!