博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Simplify Path
阅读量:2426 次
发布时间:2019-05-10

本文共 2237 字,大约阅读时间需要 7 分钟。

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:

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

Example 2:

Input: "/../"Output: "/"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:

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

Example 4:

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

Example 5:

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

Example 6:

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

分析

给出一个Linux/Unix风格的绝对路径,要简化该路径。即将其转化成为一个标准的路径。

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

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

对于第i个字符串:

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

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

代码如下

class Solution {
public String simplifyPath(String path) {
StringBuilder result = new StringBuilder(); String[] strings = path.split("/"); for (int i = 0; i < strings.length; i++) {
if (strings[i].equals("") || strings[i].equals(".")) {
continue; } else if (strings[i].equals("..")) {
int index = result.lastIndexOf("/"); if (index >= 0) {
result.delete(index, result.length()); } } else {
result.append('/'); result.append(strings[i]); } } if (result.length() == 0) {
result.append('/'); } return result.toString(); }}

转载地址:http://iibmb.baihongyu.com/

你可能感兴趣的文章
【c语言】写一个函数返回参数二进制中 1 的个数 比如: 15 0000 1111 4 个 1
查看>>
【C语言】【编程练习】字符大小写问题
查看>>
【C语言】【编程练习】判断100到200之间的素数
查看>>
【C语言】将数组A中的内容和数组B中的内容进行交换。(数组一样大)
查看>>
【C语言】实现一个简单小游戏-三子棋
查看>>
【C语言】c语言程序编译运行过程;静态链接,动态链接;
查看>>
【C语言】数据在计算机中的存储与运算
查看>>
【计算机】什么是计算机中的大端小端
查看>>
【C语言】深入理解const,volatile,static关键字
查看>>
【C语言】c/c++程序的内存是如何分配的?
查看>>
【C语言】深入理解C语言的函数调用过程
查看>>
【C语言】C语言中格式化字符的具体用法(C语言中%的那些事)
查看>>
【java】十大经典排序算法(动图演示)
查看>>
【代码规范】google开源c\c++项目代码规范
查看>>
【C语言】c语言常用的几个函数源代码【strlen,strcpy,strcat,strstr】
查看>>
【C语言】杨辉三角问题
查看>>
【C语言】size与strlen的区别解析
查看>>
【C语言】指针深入理解-指针与数组的关系
查看>>
【C语言】C语言中常用函数源代码【strncpy ,strncat ,strncmp】
查看>>
【linux】入门学习Linux常用必会命令实例详解
查看>>