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);
        }
    }
  • 相关阅读:
    matlab:画二维正态分布密度函数图
    几个机器学习上的概念
    相似性度量
    二分图最大匹配问题
    过三关(tictactoe)游戏的LIBSVM解决方法
    关于二分图的一些概念
    用NSZombieEnabled解决恼人的EXC_BAD_ACCESS错误
    SMARTARM2200 ADS工程在IAR EWARM 5.3上的移植(1)启动代码(cstartup.s)分析
    iOS开发-用ZipArchive添加和解压zip包
    iOS程序内进入 App Store 打分的代码
  • 原文地址:https://www.cnblogs.com/nxzblogs/p/11350316.html
Copyright © 2011-2022 走看看