leetcode 100: Simplify Path

来源:互联网 发布:java独立开发 编辑:程序博客网 时间:2024/04/24 07:07

Simplify Path
Apr 4 '12

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

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

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

HAPPY 100. my goal 300~  

 

 

public class Solution {    public String simplifyPath(String path) {        // Start typing your Java solution below        // DO NOT write main() function        //path = "/a/./b/../../c/", => "/c"                if(path==null) return null;                String[] strs = path.split("/");        Stack<String> stack = new Stack<String>();                for( int i=0; i<strs.length; i++) {            String s = strs[i];            if( s.equals(".") || s.length()==0) {//!alert: s.length==0 or u will have many ////.                 continue;            } else if(s.equals("..") ) {                if(!stack.isEmpty()){                    stack.pop();                }            } else {                stack.push(s);            }         }                StringBuilder sb = new StringBuilder();                while(!stack.isEmpty()) {            sb.insert(0, stack.pop() );            sb.insert(0, "/");        }                if(sb.length()==0) sb.insert(0, "/");        return sb.toString();    }}

 

public class Solution {    public String simplifyPath(String path) {        // Start typing your Java solution below        // DO NOT write main() function        //path = "/a/./b/../../c/", => "/c"                if(path==null) return null;                String[] strs = path.split("/");        Stack<String> stack = new Stack<String>();                for( int i=0; i<strs.length; i++) {            String s = strs[i];            if( s.equals(".") || s.length()==0) {//!alert: s.length==0 or u will have many ////.                 continue;            } else if(s.equals("..") ) {                if(!stack.isEmpty()){                    stack.pop();                }            } else {                stack.push(s);            }         }                StringBuilder sb = new StringBuilder();        if(stack.isEmpty()) return "/";                Deque<String> alt = new ArrayDeque<String>();        while(!stack.isEmpty()) {            alt.push( stack.pop() );        }                while(!alt.isEmpty()) {            sb.append("/" + alt.pop());        }                return sb.toString();    }}



原创粉丝点击