zoukankan      html  css  js  c++  java
  • [leetcode]Simplify Path

    问题描写叙述:

    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.

    Corner Cases:
    • Did you consider the case where path = "/../"?
      In this case, you should return "/".
    • Another corner case is the path might contain multiple slashes '/' together, such as"/home//foo/".
      In this case, you should ignore redundant slashes and return "/home/foo".


    基本思想:

    此题能够用一个堆栈存储每层目录或文件。假设两个/之间的内容是".."就弹出栈顶元素。假设遇到“.”或“”就不变。基本思想就是这样。

    但要考虑一些corner case。如“/../”,"///"等

    代码:

    public String simplifyPath(String path) {  //Java
            // return "/";
            path = path.trim();
            if(path.equals("/"))
                return "/";
            
            List<String> stack = new LinkedList<String>();
            
            int top = -1;
            String tmp = path;
            while(!tmp.equals("")){
                if(tmp.startsWith("/"))
                     tmp = tmp.substring(1);
                if(tmp.equals(""))
                    break;
                
                if(tmp.contains("/")){
                    int pos = tmp.indexOf("/");
                    String file = tmp.substring(0,pos);
                    tmp = tmp.substring(pos);
                    if(file.equals(".")|| file.equals(""))
                        continue;
                    if(file.equals("..")){
                        if(top>-1)
                            top--;
                        continue;   
                    }
                    stack.add(++top,file);
                    
                }
                else {
                    String file = tmp;
                    tmp = "";
                    if(file.equals("."))
                        continue;
                    if(file.equals("..")){
                        if(top>-1)
                            top--;
                        continue;   
                    }
                    stack.add(++top,file);
                    
                }
            }
            //generate path;
            String rpath = "/";
            for(int i = 0; i <=top ; i++)
                rpath += stack.get(i)+"/";
            if(top >=0)
                rpath = rpath.substring(0,rpath.length()-1);
            return rpath;
            
        }


  • 相关阅读:
    UVA 401 回文词
    n的阶乘分解成素数幂的积
    DSSM问答匹配模型
    Enhanced LSTM for Natural Language Inference
    Bidirectional LSTM-CRF Models for Sequence Tagging
    Attention Is All You Need 学习笔记
    BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding
    C++学习笔记(四)
    C++学习笔记(三)
    java学习笔记(七)
  • 原文地址:https://www.cnblogs.com/yjbjingcha/p/8417528.html
Copyright © 2011-2022 走看看