//简化一个路径
public String simplifyPath(String path) {
if(path==null || path.length()==0)
return "";
StringBuilder res=new StringBuilder();
int len=path.length();
int i=0;
Stack<String> st=new Stack<String>();
while(i<len)
{
if(path.charAt(i)=='/')
i++;
else
{
int j=i+1;
while(j<len && path.charAt(j)!='/')
j++;
String temp=path.substring(i,j);
if(temp.length()==1&&temp.charAt(0)=='.')
i++;
else if(temp.length()==2&& temp.charAt(0)=='.'&&temp.charAt(1)=='.') // ".." 这种
{
//出栈
if(!st.isEmpty())
st.pop();
i=j;
}
else
{
st.push(temp);
i=j;
}
}
}
if(st.isEmpty())
{
return "/";
}
else
{
while(!st.isEmpty())
{
res.insert(0,"/"+st.pop());
}
return res.toString();
}
}
leetcode 71. Simplify Path
最新推荐文章于 2024-10-01 05:07:35 发布