0
点赞
收藏
分享

微信扫一扫

LeetCode-071-简化路径

有态度的萌狮子 2021-09-28 阅读 24
LeetCode

简化路径

解法一:利用栈
import java.util.Stack;

public class LeetCode_071 {
    public static String simplifyPath(String path) {
        Stack<String> paths = new Stack<>();
        String str = "";
        for (char c : path.toCharArray()) {
            if (c == '/') {
                if (str.length() != 0) {
                    if (str.equals(".")) {
                    } else if (str.equals("..")) {
                        if (!paths.isEmpty()) {
                            paths.pop();
                        }
                    } else {
                        paths.push(str);
                    }
                    str = "";
                }
            } else {
                str += c;
            }
        }
        if(str.length() != 0) {
            if (str.equals(".")) {
            } else if (str.equals("..")) {
                if (!paths.isEmpty()) {
                    paths.pop();
                }
            } else {
                paths.push(str);
            }
        }
        if (paths.isEmpty()) {
            return "/";
        }
        Stack<String> reversePaths = new Stack<>();
        while (!paths.isEmpty()) {
            reversePaths.push(paths.pop());
        }
        String result = "";
        while (!reversePaths.isEmpty()) {
            result += "/" + reversePaths.pop();
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(simplifyPath("/a//b////c/d//././/.."));
    }
}
举报

相关推荐

0 条评论