Simplify Path 简化文件路径@LeetCode

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


发现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;
    }
}





评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值