Skip to content

Latest commit

 

History

History
52 lines (36 loc) · 884 Bytes

File metadata and controls

52 lines (36 loc) · 884 Bytes

Simplify Path

Problem Link

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


Pattern

  • Stack
  • String

Approach

Split the path by slash, ignore dots, and use a stack to process directory names.


Time Complexity

O(n)

Space Complexity

O(n)


Java Solution

import java.util.*;
class Solution {
    public String simplifyPath(String path) {
        Stack<String> stack = new Stack<>();
        for (String part : path.split("/")) {
            if (part.equals("") || part.equals(".")) continue;
            if (part.equals("..")) {
                if (!stack.isEmpty()) stack.pop();
            } else {
                stack.push(part);
            }
        }
        StringBuilder ans = new StringBuilder();
        for (String dir : stack) ans.append('/').append(dir);
        return ans.length() == 0 ? "/" : ans.toString();
    }
}