Description:
Given an absolute path for a file (Unix-style), simplify it.
Solution:
用scanner和stack处理即可,用"/"作为分割器,然后每次遇到".."就出栈。最后将stack倒序输出即可。
import java.util.*;
public class Solution {
public String simplifyPath(String path) {
Scanner scan = new Scanner(path);
scan.useDelimiter("/");
String temp;
Stack<String> stack = new Stack<>();
while (scan.hasNext()) {
temp = scan.next();
if (temp.equals("..")) {
if (!stack.isEmpty())
stack.pop();
} else if (temp.equals(".")) {
} else if (temp.equals("")) {
} else {
stack.add(temp);
}
}
String ans = "";
while (!stack.isEmpty()) {
temp = stack.pop();
if (temp.equals(" "))
break;
ans = "/" + temp + ans;
}
if (ans.equals(""))
ans = "/";
// System.out.println(ans);
return ans;
}
}