思路一:
這題有點坑,不過也是自己不夠熟悉文件路徑導致的,“.”超過三個及以上就是普通文件夾或文件的名了
做法是先用棧去掉多餘的“/”,然後在將字符串分爲一個個的小段,這樣判斷路徑是什麼類型就比較容易了
class Solution {
public String simplifyPath(String path) {
Stack<Character>stk = new Stack<Character>();
String st;
for(int i=0;i<path.length();i++){
if(path.charAt(i)=='/'){
if(stk.empty()){
stk.push(path.charAt(i));
continue;
}
if(stk.peek()=='/'){
continue;
}else{
stk.push(path.charAt(i));
}
}
else{
stk.push(path.charAt(i));
}
}
StringBuilder stri = new StringBuilder();
while(!stk.empty()){
stri.insert(0,stk.pop());
}
String pm = stri.toString();
Stack<String>stk1 = new Stack<String>();//字符串棧
String[] om = pm.substring(1).split("/");//將其作爲一個個字符串處理容易判斷類型
//這裏之所以從1 開始截取是開頭也有"/"
for(int i =0;i<om.length;i++){
if(om[i].length()==2&&om[i].charAt(0)=='.'&&om[i].charAt(1)=='.'){
if(stk1.empty()){
continue;
}else{
stk1.pop();
}
}else if(om[i].length()==1&&om[i].charAt(0)=='.'){
continue;
}else{
stk1.push(om[i]);
}
}
if(stk1.empty()){
return "/";
}else {
String p ="";
while(!stk1.empty()){
p="/"+stk1.peek()+p;
stk1.pop();
}
return p;
}
}
}
思路二:
思路一的簡化
class Solution {
public String simplifyPath(String path) {
Stack<String>stk = new Stack<String>();
int i=0;
while(i<path.length()){
while(i<path.length()&&path.charAt(i)=='/'){
i++;
}
String s = "";
while(i<path.length()&&path.charAt(i)!='/'){
s+=String.valueOf(path.charAt(i++));
}
// System.out.println(s);
if(s.equals("..")&&!stk.empty()){
stk.pop();
}else if(!s.equals(".")&&!s.equals("")&&!s.equals("..")){
stk.push(s);
}
//System.out.println(i);
}
//StringBuilder st = new StringBuilder();
String sm="";
if(stk.empty()){
return "/";
}
while(!stk.empty()){
sm = "/"+stk.peek()+sm;
stk.pop();
}
return sm;
}
}