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);
    }
}
原文地址:https://www.cnblogs.com/nxzblogs/p/11350316.html