Simplify Path

         除夕夜,抢红包之余,更下博,祝所有人新年快乐,开心最重要!!!

         leetcode第71题,题目描述如下:

Given an absolute path for a file (Unix-style), simplify it.
For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c"

      翻译一下就是:把linux里的全路径改写成简单路径,比如说/home/a/b/c/../../..,其实就是/home 

       感觉不难,其实就是用栈,碰到..的话,出栈,碰到其他的入栈,最后把栈里元素输出。

      代码:

/**
	 * simplifyPath:
	 * 
	 * @param path
	 * @return String 返回类型
	 */
	public static String simplifyPath(String path) {
		if (path == null || !path.contains("/")) {
			return "/" + path == null ? "" : path;
		}
		String[] paths = path.split("/");
		StringBuilder sb = new StringBuilder();
		// 栈,保存路径信息
		Stack<String> skPath = new Stack<String>();
		for (String p : paths) {
			if (p.trim().length() == 0) {
				continue;
			}
			if (p.equals("..")) {
				if (skPath.isEmpty() || skPath.peek().equals("..")) {
				} else {
					skPath.pop();
				}
			} else if (!p.equals(".")) {
				skPath.push(p);
			}
		}
		if(skPath.isEmpty()){
			return "/";
		}
		while (!skPath.isEmpty()) {
			sb.insert(0, "/" + skPath.pop());
		}
		return sb.toString();
	}

 测试代码:

/**
	 * main:
	 * 
	 * @param args
	 *            void 返回类型
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(simplifyPath("/a/./b/../../c/"));
	}

 结果:/c

 

猜你喜欢

转载自709002341.iteye.com/blog/2276065