Lexi's Leetcode solutions

[leetcode] Simplify Path | Unix绝对路径simplify

Posted on: October 31, 2013

这个题一开始自己做死了,后来bf给讲用stack之后就一遍过了,代码也简单很多。思路

  1. 先用/来split string
  2. 然后看每一小段,若是”.”或者是“”(说明两个/连着),不入栈;若是”..”,pop;若是正常,push
  3. 最后再用string builder把”/”和栈中元素一个一个连起来。
public String simplifyPath(String path) {
    Stack<String> s = new Stack<String>();
    String[] split = path.split("/");
    for (String a : split) {
        if (!a.equals(".") && !a.isEmpty()) {
            if (a.equals("..")) {
                if (!s.isEmpty()) {
                    s.pop();
                }
            } else {
                s.push(a);
            }
        }
    }
    StringBuilder sb = new StringBuilder();
    while (!s.isEmpty()) {
        sb.insert(0, s.pop());
        sb.insert(0, "/");
    }
    return sb.length() == 0 ? "/" : sb.toString();
}

Leave a comment

Blog Stats

  • 223,397 hits
October 2013
M T W T F S S
 123456
78910111213
14151617181920
21222324252627
28293031