Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
題目不難,利用正則表達式以"/"爲分隔符進行分割,將"",".",".."的其他所有字符串壓棧,碰到一次".."將棧中的字符串彈出(如果棧不爲空的話),
最後出棧返回字符串。
public class Solution {
public String simplifyPath(String path) {
String [] list=path.split("/");
Stack<String> stack=new Stack<String>();
int len=list.length;
String res="";
for(int i=0;i<len;i++)
{
if(list[i].equals("") || list[i].equals(".")||list[i].equals(" "))continue;
if(list[i].equals(".."))
{
if(!stack.isEmpty())stack.pop();
continue;
}
stack.add(list[i]);
}
if(stack.isEmpty())return "/";
while(!stack.isEmpty())
{
res="/"+stack.pop()+res;
}
return res;
}
}