Simplify Path

今天药忘吃喽~ 2023-06-10 15:27 81阅读 0赞

Simplify Path

文章目录

  • Simplify Path
    • 题目
    • 分析
    • 代码如下

题目

题目链接:https://leetcode.com/problems/simplify-path

Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.

In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level.

Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.

Example 1:

  1. Input: "/home/"
  2. Output: "/home"
  3. Explanation: Note that there is no trailing slash after the last directory name.

Example 2:

  1. Input: "/../"
  2. Output: "/"
  3. Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.

Example 3:

  1. Input: "/home//foo/"
  2. Output: "/home/foo"
  3. Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.

Example 4:

  1. Input: "/a/./b/../../c/"
  2. Output: "/c"

Example 5:

  1. Input: "/a/../../b/../c//.//"
  2. Output: "/c"

Example 6:

  1. Input: "/a//bc/d//././/.."
  2. Output: "/a/b/c"

分析

给出一个Linux/Unix风格的绝对路径,要简化该路径。即将其转化成为一个标准的路径。
我们知道,在Linux/Unix中,路径名是以/开头的。.表示当前目录,..表示上一层目录。/表示根目录,其上一层目录仍然为根目录/。不能以/结尾(根目录只有一个/)。
需要注意的是,连续出现n个/,实际上也仅仅代表一个/,例如/home///user其实就是/home/user

因此,我们可以使用/分割当前字符串,然后遍历得到的字符串数组。
对于第i个字符串:

  • 当该字符串是空串""或者是".",路径不变。
  • 当该字符串是".."时,表示上一层路径,此时删除结果字符串最后一个目录。如果结果字符串为"",则保持不变。
  • 其他情况下,添加/和当前字符串的值到结果字符串中。

最后,当结果字符串的长度为0时,添加/,然后返回。不为0时直接返回。

代码如下

  1. class Solution {
  2. public String simplifyPath(String path) {
  3. StringBuilder result = new StringBuilder();
  4. String[] strings = path.split("/");
  5. for (int i = 0; i < strings.length; i++) {
  6. if (strings[i].equals("") || strings[i].equals(".")) {
  7. continue;
  8. } else if (strings[i].equals("..")) {
  9. int index = result.lastIndexOf("/");
  10. if (index >= 0) {
  11. result.delete(index, result.length());
  12. }
  13. } else {
  14. result.append('/');
  15. result.append(strings[i]);
  16. }
  17. }
  18. if (result.length() == 0) {
  19. result.append('/');
  20. }
  21. return result.toString();
  22. }
  23. }

发表评论

表情:
评论列表 (有 0 条评论,81人围观)

还没有评论,来说两句吧...

相关阅读