老师您好,可否发一下您关于leetcode71题的代码?谢谢

来源:6-1 栈的基础应用 Valid Parentheses

manbaneverout

2020-02-10

如题

写回答

2回答

戴JAVA老师的小迷弟

2020-05-19

public class Solution {

    public String simplifyPath(String path) {

        if(path==null)return null;

        Stack<String> stack = new Stack<>();

        String[] pathSplited = path.split("/");

        for(String temp:pathSplited){

            if (temp.equals("..")){

                if(!stack.isEmpty()){

                    stack.pop();

                }

            }

            else {

                if(!temp.equals("")&&!temp.equals(".")){

                    stack.add(temp);

                }

            }

        }

        StringBuilder sb = new StringBuilder();

        while (!stack.empty()){

            sb.insert(0,stack.pop());

            sb.insert(0,"/");

        }

        String answer = sb.toString();

        if (answer.equals(""))return "/";

        else return sb.toString();

    }

}


1
0

liuyubobobo

2020-02-11

参考这里:https://github.com/liuyubobobo/Play-Leetcode/blob/master/0071-Simplify-Path/cpp-0071/main.cpp


整体思路:使用一个栈追踪路径,遇到 . 不变,遇到 .. 退栈一个元素,其他目录入栈。

最后栈里的内容整理就是结果目录。


继续加油!:)

0
0

玩转算法面试-- Leetcode真题分门别类讲解

课程配套大量BAT面试真题,高频算法题解析,强化训练

7435 学习 · 1159 问题

查看课程