[leetcode]Simplify Path
用了个数组来存路径。遇'.'跳过,遇'..'回退。看了一下别人的,和我的思路一样,只是人家用了stack。我用了原始的arraylist而已。
参考里的答案用了String[] splits = path.trim().split("/"); 商业代码这么写肯定好,这里如果用i,j,更好练习面试而已。
public class Solution {
public String simplifyPath(String path) {
// Start typing your Java solution below
// DO NOT write main() function
if (path == null || path.length() == 0) return "/";
int len = path.length();
ArrayList<String> array = new ArrayList<String>();
int i = 0;
int j = 0;
while (i < len) {
while (i < len && path.charAt(i) == '/') {
i++;
}
j = i;
while (i < len && path.charAt(i) != '/') {
i++;
}
if (j != len) {
String tmp = "";
if (i == len) {
tmp = path.substring(j);
}
else {
tmp = path.substring(j, i);
}
if (tmp.equals(".")) {
// do nothing
}
else if (tmp.equals("..")) {
if (array.size() != 0) {
array.remove(array.size() - 1);
}
}
else {
array.add(tmp);
}
}
}
StringBuilder sb = new StringBuilder();
for (int x = 0; x < array.size(); x++) {
sb.append('/');
sb.append(array.get(x));
}
String ret = sb.toString();
if (ret.length() == 0) return "/";
else return ret;
}
}

浙公网安备 33010602011771号