Wednesday, February 4, 2015

Simplify Path LeetCode

Use stack to store the string between "/".
Similiar idea with Valid parentheses, reverse polish notation.
public String simplifyPath(String path) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
      if (path==null || path.length()==0) return "/";
     
      Stack<String> stack = new Stack<String>();
      String[] splits = path.trim().split("/");
     
      for (String str : splits) {
          if (str==null || str.length()==0 || str.equals(".")) {
             
          } else if (str.equals("..")) {
              if (stack.size() > 0) stack.pop();
          } else {
              stack.push(str);
          }
      }
     
      if (stack.isEmpty()) return "/";
      StringBuilder sb = new StringBuilder();
      while (!stack.isEmpty()) {
          sb.insert(0, stack.pop());
          sb.insert(0, "/");
      }
      return sb.toString();
    }

No comments:

Post a Comment