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);
        }
    }
  • 相关阅读:
    txt到txt处理_简单版
    解析文件格式,参考模板压缩包,第二次更新
    解析文件格式,参考模板压缩包,第一次更新
    解析文件格式,参考模板压缩包
    17定义局部过滤器
    16定义全局过滤器
    15 自定义分页pagination全局组件
    14 el-dialog 基本结构
    13props 对象
    12 props 传的是数组处理
  • 原文地址:https://www.cnblogs.com/nxzblogs/p/11350316.html
Copyright © 2011-2022 走看看