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

Stack

时间:2017-09-20 23:24:08      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:leetcode   题目   ring   his   split   another   log   []   har   

【LeetCode】

LeetCode中关于栈的题目其实不算很多,用到的套路也比较单一。

71 Simplify Path。

题目描述:

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

这题其实有很大的实际应用意义,主要是对Linux/Unix系统路径的表达。

用ArrayDeque作栈的解法:

 1 class Solution {
 2     public String simplifyPath(String path) {
 3         Deque<String> stack = new ArrayDeque<>();
 4         Set<String> skip = new HashSet<>(Arrays.asList("..", ".", ""));
 5         for(String dir : path.split("/")){
 6             if(dir.equals("..") && !stack.isEmpty())
 7                 stack.pop();
 8             else if(!skip.contains(dir))
 9                 stack.push(dir);
10         }
11         String res = "";
12         for(String str : stack){
13             res = "/" + str + res;
14         }
15         return res.isEmpty() ? "/" : res;
16     }
17 }

其实上面这种解法很慢,相当的慢,在答案的排名中发现了别人的这种的解法,相当于手动模拟栈吧。

 1 class Solution {
 2     public String simplifyPath(String path) {
 3         
 4         int l = path.length(), i = 0, k = 0;
 5         char[] C = new char[l];
 6         char ch;
 7         for(;i<l; i++) {
 8             ch = path.charAt(i);
 9             if(ch!=‘/‘) {
10                 C[k++] = ch;
11                 continue;
12             }
13             
14             while(i< l-1 && path.charAt(i+1) == ‘/‘) i++;
15             if(i == l-1)
16                 break;
17             
18             if( (i<l-3 && path.charAt(i+1) == ‘.‘ && path.charAt(i+2) == ‘.‘ && path.charAt(i+3) == ‘/‘) 
19               || (i == l-3 && path.charAt(i+1) == ‘.‘ && path.charAt(i+2) == ‘.‘)
20               ) {
21                 while(k>0 && C[--k]!=‘/‘);
22                 i+=2;
23             } else if((i<l-2 && path.charAt(i+1) == ‘.‘ && path.charAt(i+2) == ‘/‘)
24                      || (i == l-2 && path.charAt(i+1) == ‘.‘ )
25                      ) {
26                 i++;
27             } else 
28                 C[k++] = ch;
29         }
30         
31         return (k==0) ? "/" : String.valueOf(C,0,k);
32     }
33 }

 

Stack

标签:leetcode   题目   ring   his   split   another   log   []   har   

原文地址:http://www.cnblogs.com/niuxichuan/p/7565379.html

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