题目

类型:Stack

难度:中等

简化路径 - 图1

解题思路

分割字符串之后根据每种情况进行判定
.和``就不用管,直接跳过
..就代表着返回上一级,即弹出队尾元素(要注意判空)
其他情况直接压入队列就行。

代码

  1. class Solution {
  2. public String simplifyPath(String path) {
  3. // 双端队列
  4. Deque<String> queue = new LinkedList<>();
  5. // 分割字符
  6. String[] res = path.split("/");
  7. for(int i = 0; i < res.length; i++){
  8. String s = res[i];
  9. if(s.equals(".") || s.equals("")) continue;
  10. else if (s.equals("..")){
  11. if(!queue.isEmpty()){
  12. queue.pollLast();
  13. }
  14. }else{
  15. queue.offer(s);
  16. }
  17. }
  18. // 拼接
  19. StringBuilder sb = new StringBuilder("/");
  20. while(!queue.isEmpty()){
  21. sb.append(queue.poll());
  22. if(!queue.isEmpty()){
  23. sb.append("/");
  24. }
  25. }
  26. // 判空
  27. return sb.toString().equals("") ? "/" : sb.toString();
  28. }
  29. }