Stack
Posted tatarget
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Stack相关的知识,希望对你有一定的参考价值。
【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的主要内容,如果未能解决你的问题,请参考以下文章
Android - 在单个活动应用程序中使用工具栏按钮弹出 Back Stack