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

【Leetcode】 Simplify Path

时间:2016-05-30 15:15:37      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:https://leetcode.com/problems/simplify-path/

题目:

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

思路:

easy

算法

public String simplifyPath(String path) {  
        String s[] = path.trim().split("\\/+");  
        Stack<String> stack = new Stack<String>();  
  
        for (String str : s) {  
            if (!str.equals("") && !str.equals(" ") && !str.equals(".") && !str.equals("..")) {  
                stack.push(str);  
            } else if (str.equals("..") && stack.size() != 0) {  
                stack.pop();  
            }  
        }  
        String res = "";// 将栈中剩余元素组合成路径  
        for (int i = 0; i < stack.size(); i++) {  
            res = "/" + stack.get(stack.size() - 1 - i) + res;  
        }  
        if (res.equals("")) // 防止/../情况  
            res = "/";  
        return res;  
    }  


【Leetcode】 Simplify Path

标签:

原文地址:http://blog.csdn.net/yeqiuzs/article/details/51527078

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