您的位置:首页 > 其它

Simplify Path 简化文件路径@LeetCode

2013-11-24 11:38 483 查看
用栈来做,先把输入字符串以'/'为分隔符分来,如果遇到'.'或者空输入什么都不做。如果遇到'..'就弹栈。然后每从栈里退出一个元素就用'/'连接起来,注意顺序。

发现Java里面的LinkedList实现了栈和队列的所有方法,而且还有重复的!值得注意的是,LinkedList中的pop()对应的是remove()或者removeHead()  即从链表头移除,而不是removeLast()。所以在LinkedList中,进栈(push())出栈(pop())都是在链表头部进行,进队列(add())是从尾部进入,出队列是从头部被移除(remove())。

package Level3;

import java.util.LinkedList;
import java.util.Stack;

/**
* Simplify Path
*
*Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
click to show corner cases.

Corner Cases:
Did you consider the case where path = "/../"?
In this case, you should return "/".
Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
In this case, you should ignore redundant slashes and return "/home/foo".
*/
public class S71 {

public static void main(String[] args) {
String path = "/home//foo/";
System.out.println(simplifyPath(path));
}

public static String simplifyPath(String path) {
if(path.length() == 0){
return path;
}

String[] splits = path.split("/");
LinkedList<String> stack = new LinkedList<String>();
for (String s : splits) {
if(s.length()==0 || s.equals(".")){
continue;
}else if(s.equals("..")){
if(!stack.isEmpty()){
stack.pop();
}
}else{
stack.push(s);
}
}

if(stack.isEmpty()){
stack.push("");
}
String ret = "";
while(!stack.isEmpty()){
ret += "/" + stack.removeLast();
}

return ret;
}

}


public class Solution {
public String simplifyPath(String path) {
String[] ss = path.split("/");
LinkedList<String> ll = new LinkedList<String>();
for(int i=0; i<ss.length; i++) {
if(!ll.isEmpty() && ss[i].equals("..")) {
ll.removeLast();
} else if(ss[i].length() != 0 && !ss[i].equals(".") && !ss[i].equals("..")){
ll.add(ss[i]);
}
}

if(ll.isEmpty()) {
return "/";
}

String s = "";
while( !ll.isEmpty() ) {
s += "/";
s += ll.remove();
}
return s;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: