[leetcode] Simplify Path | Unix绝对路径simplify
Posted October 31, 2013
on:这个题一开始自己做死了,后来bf给讲用stack之后就一遍过了,代码也简单很多。思路
- 先用/来split string
- 然后看每一小段,若是”.”或者是“”(说明两个/连着),不入栈;若是”..”,pop;若是正常,push
- 最后再用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(); }
Tags: stack/queue
Leave a comment