zoukankan      html  css  js  c++  java
  • leetcode-71-简化路径

    问题:

    package com.example.demo;
    
    import java.util.Stack;
    
    public class Test71 {
    
    
        /**
         * 利用栈数据结果,当前元素为".."时,将栈中的元素pop出一个,
         * 当前元素部位"."并且部位“”空时,压入栈中,
         * 最后遍历栈,使用“/"连接即可
         */
        public String simplifyPath(String path) {
            StringBuffer sb = new StringBuffer();
            String[] split = path.split("/");
            Stack stack = new Stack();
            for (String s : split) {
                if ("..".equals(s)) {
                    if (!stack.isEmpty()) {
                        stack.pop();
                    }
                } else if (!".".equals(s) && !"".equals(s)) {
                    stack.push(s);
                }
            }
            sb.append("/");
            if (!stack.isEmpty()) {
                for (Object o : stack) {
                    sb.append((String) o);
                    sb.append("/");
                }
                return sb.substring(0, sb.lastIndexOf("/"));
            }
            return sb.toString();
        }
    
        public static void main(String[] args) {
            Test71 t = new Test71();
            String s = t.simplifyPath("/../");
            System.out.println(s);
        }
    }
    package com.example.demo;
    
    import java.util.Stack;
    
    public class Test71 {
    
    
        /**
         * 利用栈数据结果,当前元素为".."时,将栈中的元素pop出一个,
         * 当前元素部位"."并且部位“”空时,压入栈中,
         * 最后遍历栈,使用“/"连接即可
         */
        public String simplifyPath(String path) {
            StringBuffer sb = new StringBuffer();
            String[] split = path.split("/");
            Stack stack = new Stack();
            for (String s : split) {
                if ("..".equals(s)) {
                    if (!stack.isEmpty()) {
                        stack.pop();
                    }
                } else if (!".".equals(s) && !"".equals(s)) {
                    stack.push(s);
                }
            }
            sb.append("/");
            if (!stack.isEmpty()) {
                for (Object o : stack) {
                    sb.append((String) o);
                    sb.append("/");
                }
                return sb.substring(0, sb.lastIndexOf("/"));
            }
            return sb.toString();
        }
    
        public static void main(String[] args) {
            Test71 t = new Test71();
            String s = t.simplifyPath("/../");
            System.out.println(s);
        }
    }
  • 相关阅读:
    解析URL
    文件上传
    MyEclipse自动生成hibernate实体类和配置文件攻略
    <form>表单提交时注意
    W2UI /W2Toolbar的click响应事件
    JS 读写文件
    select 美化(bootstrap)
    安装MySQL for Windows 数据库
    java环境配置—配置Tomcat8环境
    对进程、线程、应用程序域的理解
  • 原文地址:https://www.cnblogs.com/nxzblogs/p/11350316.html
Copyright © 2011-2022 走看看