Pages

Wednesday, October 1, 2025

leetcode. 71: Simplify Path (Stacks question)

 class Solution {

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

        for(String comp : components) {
            if(comp.equals(".") || comp.equals("")) {
                continue;
            }
            if(comp.equals("..")) {
                if(!st.isEmpty()) {
                    st.pop();
                }
            } else {
                st.push(comp);
            }
            }
            StringBuilder sb = new StringBuilder();
            for(String str1 : st) {// st will have stored everything
                sb.append("/").append(str1);
        }
        return sb.length() == 0 ? "/" : sb.toString();
        }
    }

No comments:

Post a Comment

3Sum - Leetcode solution - How i turned into two-pointer approach?

  class Solution {     public List < List < Integer >> threeSum ( int [] nums ) {         Arrays . sort (nums); // first sort...