LeetCode:Simplify Path

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

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

題目不難,利用正則表達式以"/"爲分隔符進行分割,將"",".",".."的其他所有字符串壓棧,碰到一次".."將棧中的字符串彈出(如果棧不爲空的話),

最後出棧返回字符串。

public class Solution {
    public String simplifyPath(String path) {
        String [] list=path.split("/");
        Stack<String> stack=new Stack<String>();
        int len=list.length;
        String res="";
        for(int i=0;i<len;i++)
        {   
            if(list[i].equals("") || list[i].equals(".")||list[i].equals(" "))continue;
            if(list[i].equals(".."))
            {
                if(!stack.isEmpty())stack.pop();
                continue;
            }
            stack.add(list[i]);
        }
        if(stack.isEmpty())return "/";
        while(!stack.isEmpty())
        {
            res="/"+stack.pop()+res;
        }
        return res;
    }
}


發佈了34 篇原創文章 · 獲贊 0 · 訪問量 9653
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章