package com.zerroi.leetcode.Three21; import java.util.Queue; import java.util.Stack; public class SimplifyPath { public static void main(String[] args) { SolutionSecond solutionSecond = new SolutionSecond(); // String s = solutionSecond.simplifyPath("/a//b////c/d//././/.."); String s = solutionSecond.simplifyPath("/../"); System.out.println("s = " + s); } } class SolutionSecond { public String simplifyPath(String path) { String[] strs = path.split("/"); Stack stack = new Stack<>(); for (String str : strs) { if ("..".equals(str)) { if (!stack.isEmpty()) stack.pop(); } else if (!str.isEmpty() && !str.equals(".")) { stack.push(str); } } StringBuffer res = new StringBuffer(); if (stack.isEmpty()) { res.append("/"); } else { while (!stack.isEmpty()) { res.append("/"); res.append(stack.removeFirst()); } } return res.toString(); } }