1. 程式人生 > 其它 >Java 環境準備

Java 環境準備

package leetcode;

import java.util.Stack;

public class demo_71 {
    public String simplifyPath(String path) {
        String[] str=path.split("/");
        Stack<String> stack=new Stack<String>();
        Stack<String> sta=new Stack<String>();
        //把地址按"/"進行分割,然後存入一個棧中
        for
(String s:str) { //防止空棧 if(stack.empty()) { stack.push("/"); } //分割後的空格和"."都捨棄 if(s.equals(".")||s.equals("")) { continue; } //如果是回退,則彈出頂層 if(s.equals("..")) { stack.pop(); }
//否則存入棧中 else { stack.push(s); } } path=""; //存入棧的地址是相反的,所以存入另外一個棧進行修正 while(!stack.empty()) { sta.push(stack.pop()); } if(!sta.empty()&&sta.peek().equals("/")) { sta.pop(); }
while(!sta.empty()) { path=path+"/"+sta.pop(); } if(path.equals("")) {path=path+"/";} System.out.println(path); return path; } public static void main(String[] args) { // TODO Auto-generated method stub demo_71 d71=new demo_71(); String path="///a/./b/../../c/"; d71.simplifyPath(path); } }