zoukankan      html  css  js  c++  java
  • Simplify Path——LeetCode

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

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

    题目大意:给一个String,表示一个文件的绝对路径,简化它。

    解题思路:用一个栈表示即可,..向上返回一层,就是出栈一个元素,.不做操作,其他的入栈。

    public class Solution {
        public String simplifyPath(String path) {
            if (path == null || path.length() == 0) {
                return null;
            }
            Deque<String> deque = new ArrayDeque<>();
            String[] dirs = path.split("/");
            for (String dir : dirs) {
                if (".".equals(dir)){
                    continue;
                }
                else if ("..".equals(dir)) {
                    if (!deque.isEmpty()) {
                        deque.pop();
                    }
                } else {
                    if(dir==null||dir.length()==0){
                        continue;
                    }
                    deque.push(dir);
                }
            }
            String res = "/";
            while (!deque.isEmpty()) {
                res += deque.pollLast();
                res += "/";
            }
            res = res.substring(0, res.length() > 1 ? res.length() - 1 : 1);
            return res;
        }
    }
  • 相关阅读:
    iOS开源控件库收集
    Ruby中的几种除法
    Font
    PlaySound
    STL
    APIs
    cin and cout
    CreateWindow
    Introducing Direct2D
    VC 常用代码
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4599762.html
Copyright © 2011-2022 走看看