[leetcode] 题型整理之字符串处理

71. Simplify Path

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

Corner Cases:

    • Did you consider the case where path = "/../"?
      In this case, you should return "/".
    • Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
      In this case, you should ignore redundant slashes and return "/home/foo".

java的split函数,只要separator的前“或者”后没有“别的”字符串就会返回一个空。

linux系统当中,多余两个的点会被当作普通路径处理。

public class Solution {
public String simplifyPath(String path) {
if (path.length() == 0) {
return "";
}
String[] strs = path.split("/");
StringBuilder result = new StringBuilder();
LinkedList<String> stack = new LinkedList<String>();
for (String string : strs) {
switch (string) {
case "": stack.offer("/"); break;
case ".": break;
case "..": while (!stack.isEmpty() && stack.removeLast().equals("/")); break;
default: stack.offer(string);
}
}
if (path.charAt(0) == '/') {
result.append('/');
}
while (!stack.isEmpty()) {
String string = stack.removeFirst();
if (!string.equals("/")) {
result.append(string);
result.append('/');
}
}
int ll = result.length();
if (ll > 1 && result.charAt(ll - 1) == '/') {
result.deleteCharAt(ll - 1);
}
return result.toString();
}
}
上一篇:uva 401.Palindromes


下一篇:Slick – 这是你需要的最后一款 jQuery 传送带插件