【leetcode】71.(Medium)Simplify Pathes
阿新 • • 發佈:2018-11-22
解題思路:
用一個List(pathes)維護有效路徑,遇到有效的路徑就加進pathes裡面,遇到“. .”先看pathes是否為空,為空就不管,不為空就刪掉pathes中的最後一個有效路徑。
最後將這個記錄了有效路徑的List(pathes)轉化為String的格式並返回。
提交程式碼:
class Solution {
public String simplifyPath(String path) {
int p1=0,p2=1;
List<String> pathes=new ArrayList<String> ();
String curPath="";
while(p2<path.length()) {
while(p2<path.length()&&path.charAt(p2)!='/')
p2++;
if(p2==p1+1) {
p1=p2; p2++;continue;
}
if(path.substring(p1+1,p2).equals(".")) {
p1=p2; p2++;continue;
} else if(path.substring(p1+1,p2).equals("..")) {
if(pathes.size()!=0)
pathes.remove(pathes.size()-1);
p1=p2; p2++; continue;
}
pathes.add(path.substring(p1+1, p2));
p1=p2;p2++;
}
if(pathes.size()==0) return "/";
for(int i=0;i<pathes. size();i++)
curPath+=("/"+pathes.get(i));
return curPath;
}
}
執行結果: