程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> LeetCode | Simplify Path

LeetCode | Simplify Path

編輯:C++入門知識

題目

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". 分析

    java自帶的split函數,以及Stack迭代器的遍歷順序都完全符合這題的要求。

    代碼

    import java.util.Stack;
    
    public class SimplifyPath {
    	public String simplifyPath(String path) {
    		Stack stack = new Stack();
    		String[] array = path.split("/");
    		for (int i = 0; i < array.length; ++i) {
    			if (array[i].length() == 0 || array[i].equals(".")) {
    				continue;
    			} else if (array[i].equals("..")) {
    				if (!stack.isEmpty()) {
    					stack.pop();
    				}
    			} else {
    				stack.push(array[i]);
    			}
    		}
    		StringBuilder sb = new StringBuilder("/");
    		for (String e : stack) {
    			sb.append(e).append("/");
    		}
    		return sb.length() == 1 ? sb.toString() : sb.substring(0,
    				sb.length() - 1).toString();
    	}
    }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved