Simplify Path

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) {

        if(path == null || path.length() == 0)  return "";

        String[] paths = path.split("/");

        Stack<String> stack = new Stack<String>();

        for(String str: paths)

        {

            if(str.equals("")) continue;

            if(str.equals("."))

            {}

            else if(str.equals(".."))

            {

                if(!stack.isEmpty()) stack.pop();

            }

            else

                stack.push(str);

        }

        String rst = new String();

        while(!stack.isEmpty())

        {

            rst = "/"+ stack.pop() + rst;

        }

        if(rst.equals(""))  return "/";

        return rst;

    }

}
View Code

 

你可能感兴趣的:(Path)