[LeetCode]Simplify Path

来源:互联网 发布:好吃的肉类零食知乎 编辑:程序博客网 时间:2024/06/03 23:02

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

string.split的时候如果两个标志之间没有值也会返回一个空字符串,stack用ArrayDeque,“/..”和“/home//test”都是合法输入


public class Solution {    public String simplifyPath(String path) {        if (path == null) return path;        String[] arr = path.split("/");        Deque<String> stack = new ArrayDeque<>();        for (int i = 0; i < arr.length; i++) {            if (arr[i].equals(".") || arr[i].length() == 0) continue;            else if (arr[i].equals("..")) {                if (!stack.isEmpty()) stack.pop();            }            else stack.push(arr[i]);        }        StringBuilder sb = new StringBuilder();        while (!stack.isEmpty()) {            sb.insert(0, "/" + stack.pop());        }        return sb.length() == 0 ? "/" : sb.toString();    }}


0 0
原创粉丝点击