码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Simplify Path

时间:2014-09-27 17:21:00      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   java   strong   for   sp   

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".
 
Solution:
考察Java String的split function。
 
  1. 先用/来split string
  2. 然后看每一小段,若是”.”或者是“”(说明两个/连着),不入栈;若是”..”,pop;若是正常,push.
 
 1 public class Solution {
 2     public String simplifyPath(String path) {
 3         if(path==null||path.length()==0)
 4             return "";
 5         if(path.equals("/"))
 6             return "/";
 7         String[] tokens=path.split("/");
 8         Stack<String> stack=new Stack<String>();
 9         
10         for(int i=0;i<tokens.length;++i){
11             if(tokens[i].equals("..")){
12                 if(!stack.empty())
13                     stack.pop();
14                 else
15                     continue;
16             }else if(tokens[i].equals(".")||tokens[i].length()==0){
17                 continue;
18             }else{
19                 stack.push(tokens[i]);
20             }
21         }
22         
23         Stack<String> stack2=new Stack<String>();
24         String result=new String("");
25         
26         if(stack.empty())
27             return "/";
28         
29         while(!stack.empty())
30             stack2.push(stack.pop());
31         while(!stack2.empty()){
32             result+="/";
33             result+=stack2.pop();
34         }
35         return result;   
36     }
37 }

 

[Leetcode] Simplify Path

标签:style   blog   http   color   io   java   strong   for   sp   

原文地址:http://www.cnblogs.com/Phoebe815/p/3996438.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!