DEV Community

Debesh P.
Debesh P.

Posted on

71. Simplify Path | LeetCode | Top Interview 150 | Coding Questions

Problem Link

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


Detailed Step-by-Step Explanation

https://leetcode.com/problems/simplify-path/solutions/7566828/optimal-solution-beats-100-multiple-lang-lf3h


leetcode 71


Solution

class Solution {
    public String simplifyPath(String path) {

        Stack<String> st = new Stack<>();
        String[] components = path.split("/");

        for (String component : components) {

            if (component.equals("") || component.equals(".")) {
                continue;
            }

            if (component.equals("..")) {
                if (!st.isEmpty()) {
                    st.pop();
                }
            } else {
                st.push(component);
            }
        }

        if (st.isEmpty()) {
            return "/";
        }

        StringBuilder res = new StringBuilder();
        for (String dir : st) {
            res.append("/").append(dir);
        }

        return res.toString();
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)