Java easy to understand solution with StringTokenizer


  • 0
    H
    import java.util.StringTokenizer;
    public class Solution {
        public String simplifyPath(String path) {
            StringBuffer res = new StringBuffer();
            StringTokenizer st = new StringTokenizer(path, "/");
            Stack<String> stack = new Stack<>();
            while (st.hasMoreTokens()) {
                String temp = st.nextToken();
                if (temp.equals(".")) continue;
                if (temp.equals("..") && !stack.empty()) stack.pop();
                else if (!temp.equals("..")) stack.push(temp);
            }
            for (String str : stack) {
                res.append("/").append(str);
            }
            return res.length() == 0 ? "/" : res.toString();
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.