zoukankan      html  css  js  c++  java
  • 71. 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".
     

    /**
    * 这是一道简化路径的题,路径简化的依据是:

    当遇到“/../"则需要返回上级目录,需检查上级目录是否为空。

    当遇到"/./"则表示是本级目录,无需做任何特殊操作。

    当遇到"//"则表示是本级目录,无需做任何操作。

    当遇到其他字符则表示是文件夹名,无需简化。

    当字符串是空或者遇到”/../”,则需要返回一个"/"。

    当遇见"/a//b",则需要简化为"/a/b"。
    *
    */

    Use two stack

    public class Solution {
        public String simplifyPath(String path) {
            String[] p = path.split("/");
            Stack<String> stack = new Stack<String>();
            for(int i = 0 ; i < p.length ; i ++){
             if(p[i].length() == 0 || p[i].equals(".")) continue;
             else if(p[i].equals("..")){
                 if(!stack.isEmpty()) stack.pop();
             }
             else stack.push(p[i]);
            }
            StringBuilder sb = new StringBuilder();
            if(stack.isEmpty()) return "/";
            
            Stack<String> temp = new Stack<String>();
            while(!stack.isEmpty()){
                temp.push(stack.pop());
            }
            
            while(!temp.isEmpty()){
                sb.append("/").append(temp.pop());
            }
            
            return sb.toString();
        }
    }
  • 相关阅读:
    一个完成的spring xml配置文件
    一个简单的Spring程序
    Spring beans.xml
    strust2的核心和工作原理
    MVC模式
    JSON 之FastJson解析
    Java本地方法(native方法)的实现
    RMI(Remote Method Invocation ) 概念恢复
    java注解
    输入sql语句,将结果写入到xml文件
  • 原文地址:https://www.cnblogs.com/joannacode/p/6105903.html
Copyright © 2011-2022 走看看