您的位置:首页 > 其它

Leetcode 71. Simplify Path

2016-01-29 23:36 423 查看
Given an absolute path for a file (Unix-style), simplify it.

For example,
path = 
"/home/"
, => 
"/home"

path = 
"/a/./b/../../c/"
, => 
"/c"


So why we need to change the format of the String address. cause the format of the string address
given is not a standard


format, so we need to turn it into a standard format.


The address string is split by some string, then we need to use this string array to construct
the result..


There are different condition 


1 if the string array is '.' or '' that means that the the length of the string is 0, then just 


continue, 

2 if the string splited is '..', then if the
stack is not empty, then just pop the stack.
3 if the string is not the case above, then
just push the string into the stack.
4 and then pop the string in the stack in
the order and construct the final result.
the only way I know is to append the poped
string to the end of the result string.w
public class Solution {
public String simplifyPath(String path) {
if(path == null || path.length() == 0)
return path;
Stack<String>stack = new Stack<String>();
String[] temRes = path.split("/");
for(int i = 0; i < temRes.length; i++){
if(temRes[i].equals(".") || temRes[i].length() == 0)
continue;
else if(temRes[i].equals("..")){
if(!stack.isEmpty()){
stack.pop();
}
}
else{
stack.push(temRes[i]);
}
}
//I use two stack to reverse the make the order of the string the same with the original string
Stack<String> reverse = new Stack<String>();
StringBuffer result = new StringBuffer();
while(!stack.isEmpty()){
reverse.push(stack.pop());
}
while(!reverse.isEmpty()){
result.append("/" + reverse.pop());
}
if(result.length() == 0)
result.append("/");
return result.toString();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: