您的位置:首页 > 其它

LeetCode-Add to List 71. Simplify Path

2017-06-20 22:20 363 查看

问题描述

给定一个Unix绝对路径,简化该路径并返回。

例如:path = “/home/”, => “/home”

path = “/a/./b/../../c/”, => “/c”

解题思路

利用栈来求解,从最左边开始依次取出两个/ /之间的字符串,如果该字符串是“..”,则在栈中弹出一个路径字符串;如果该字符串是“.”或者“”,栈保持不变;否则,将字符串压栈。然后再全部弹出组成新的路径。

代码

import java.util.Stack;
public class Solution {
public String simplifyPath(String path) {
if(path==null || path.length()==0)
return "";
Stack<String> stack=new Stack<String>();
int first=path.indexOf("/");
int second=0;
while(path.length()>0){
second=path.indexOf("/",first+1);
if(second==-1)
second=path.length();
String tem=path.substring(first+1,second);
path=path.substring(second,path.length());
if(tem.equals("..")){//比较两个字符串是否相等一定是equals而不是==!!
if(!stack.empty())
stack.pop();
}else if(tem.equals(".") || tem.equals(""))
continue;
else{
stack.push("/"+tem);
}
first=0;
}
String result="";
if(stack.empty())
return "/";
while(!stack.empty())
result=stack.pop()+result;
return result;
}
}


因为是函数的输入是绝对路径,因此字符串必然是从“/”开始,因此可以让first变量恒为0.如下所示:

import java.util.Stack;
public class Solution {
public String simplifyPath(String path) {
if(path==null || path.length()==0)
return "";
Stack<String> stack=new Stack<String>();
//int first=path.indexOf("/");
int second=0;
while(path.length()>0){
second=path.indexOf("/",0+1);
if(second==-1)
second=path.length();
String tem=path.substring(0+1,second);
path=path.substring(second,path.length());
if(tem.equals("..")){
if(!stack.empty())
stack.pop();
}else if(tem.equals(".") || tem.equals(""))
continue;
else{
stack.push("/"+tem);
}
//first=0;
}
String result="";
if(stack.empty())
return "/";
while(!stack.empty())
result=stack.pop()+result;
return result;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unix