加入收藏 | 设为首页 | 会员中心 | 我要投稿 我爱资讯网 (https://www.52junxun.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 服务器 > 搭建环境 > Unix > 正文

每日一恋 - LeetCode 71. Simplify Path(简化路径)

发布时间:2022-12-07 10:59:14 所属栏目:Unix 来源:
导读:  题目描述

  给定一个文档 (Unix-style) 的完全路径,请进行路径简化。

  例如,

  path = "/home/", => "/home"
  path = "/a/./b/../../c/", => "/c"
  边界情况:

  分析

 
  题目描述
 
  给定一个文档 (Unix-style) 的完全路径,请进行路径简化。
 
  例如,
 
  path = "/home/", => "/home"
  path = "/a/./b/../../c/", => "/c"
  边界情况:
 
  分析
 
  思路其实很简单,切割字符串后,取出每一个路径名,如果是空,跳过;如果路径中没有出现.,那么压入栈;如果包含.,就看有几个.,一个表示当前目录,无意义,三个以上根据题目要求也要压入栈。只有..一种情况需要popunix路径简化,在pop之前还要检查栈中是否有元素,没有元素也不需要进行操作。最后将剩余的路径用/连接起来即可。
 
  public String simplifyPath(String path) {
      Stack<String> stack = new Stack<String>();
      for (String s : path.split("/")) {
          if (s.isEmpty())
              continue;
          if (s.contains(".")) {
              if (s.equals(".")) {
                  continue;
              }
              if (s.equals("..")) {
                  if (stack.isEmpty()) continue;
                  stack.pop();
              }
              else {
                  stack.push(s);
              }
          }
          else {
              stack.push(s);
          }
      }
      StringBuilder sb = new StringBuilder();
      for (String s : stack) {
          sb.append("/" + s);
      }
      return sb.length() == 0 ? "/" : sb.toString();
  }
  以下是shpolsky的解决方法,与我的思路是相同的,但很简洁。
 
  public String simplifyPath(String path) {
      Deque<String> stack = new LinkedList<>();
      Set<String> skip = new HashSet<>(Arrays.asList("..",".",""));
      for (String dir : path.split("/")) {
          if (dir.equals("..") && !stack.isEmpty()) stack.pop();
          else if (!skip.contains(dir)) stack.push(dir);
      }
      String res = "";
      for (String dir : stack) res = "/" + dir + res;
      return res.isEmpty() ? "/" : res;
  }
  如果文章里有说得不对的地方请前辈多多指正~ 与君共勉~
 

(编辑:我爱资讯网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章