simplify-path

Posted 笨鸟居士的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了simplify-path相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/simplify-path/

https://leetcode.com/mockinterview/session/result/xjl3d3m/

现在字符串比较,都知道用 equals了,哈哈。不能用==,否则可能有bug。

 

package com.company;


import java.util.*;

class Solution {
    public String simplifyPath(String path) {
        Stack<String> stk= new Stack<>();
        String[] strs = path.split("/");
        for (int i=0; i<strs.length; i++) {
            if (strs[i].equals("") || strs[i].equals(".")) {
                continue;
            }
            else if (strs[i].equals("..")) {
                if (!stk.empty()) {
                    stk.pop();
                }
            }
            else {
                stk.push(strs[i]);
            }
        }

        Stack<String> newStk= new Stack<>();
        String tmp;
        while (!stk.empty()) {
            tmp = stk.pop();
            newStk.push(tmp);
        }

        StringBuilder sb = new StringBuilder();
        while (!newStk.empty()) {
            sb.append("/" + newStk.pop());
        }
        String str = sb.toString();
        if (str.equals("")) {
            str = "/";
        }
        return str;
    }
}

public class Main {

    public static void main(String[] args) throws InterruptedException {

        System.out.println("Hello!");
        Solution solution = new Solution();

        // Your Codec object will be instantiated and called as such:
        String path = "/a/./b/../../c/";
        String ret = solution.simplifyPath(path);
        System.out.printf("ret:%s\n", ret);

        System.out.println();

    }

}

 

以上是关于simplify-path的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode——simplify-path

Leetcode 71 简化路径simplify-path(栈)

71. Simplify Path

71. Simplify Path

微信小程序代码片段

VSCode自定义代码片段——CSS选择器