博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode]Simplify Path @ Python
阅读量:7224 次
发布时间:2019-06-29

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

原题地址:https://oj.leetcode.com/problems/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".
解题思路:

题目的要求是输出Unix下的最简路径,Unix文件的根目录为"/","."表示当前目录,".."表示上级目录。

例如:

输入1:

/../a/b/c/./.. 

输出1:

/a/b

模拟整个过程:

1. "/" 根目录

2. ".." 跳转上级目录,上级目录为空,所以依旧处于 "/"

3. "a" 进入子目录a,目前处于 "/a"

4. "b" 进入子目录b,目前处于 "/a/b"

5. "c" 进入子目录c,目前处于 "/a/b/c"

6. "." 当前目录,不操作,仍处于 "/a/b/c"

7. ".." 返回上级目录,最终为 "/a/b"

使用一个栈来解决问题。遇到'..'弹栈,遇到'.'不操作,其他情况下压栈。

代码一:

class Solution:    # @param path, a string    # @return a string    def simplifyPath(self, path):        stack = []        i = 0        res = ''        while i < len(path):            end = i+1            while end < len(path) and path[end] != "/":                end += 1            sub=path[i+1:end]            if len(sub) > 0:                if sub == "..":                    if stack != []: stack.pop()                elif sub != ".":                    stack.append(sub)            i = end        if stack == []: return "/"        for i in stack:            res += "/"+i        return res

代码二:

利用python的字符串处理能力。

class Solution:    # @param path, a string    # @return a string    def simplifyPath(self, path):        path = path.split('/')        curr = '/'        for i in path:            if i == '..':                if curr != '/':                    curr = '/'.join(curr.split('/')[:-1])                    if curr == '': curr = '/'            elif i != '.' and i != '':                curr += '/' + i if curr != '/' else i        return curr

 

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

你可能感兴趣的文章
数据强转
查看>>
Latest crack software ftp download
查看>>
OpenStack 的防火墙规则流程
查看>>
Overloading Django Form Fields
查看>>
03.MyBatis的核心配置文件SqlMapConfig.xml
查看>>
python学习笔记(9)-python编程风格
查看>>
Apache HTTP Server搭建虚拟主机
查看>>
(译).NET4.X 并行任务中Task.Start()的FAQ
查看>>
git log显示
查看>>
java中相同名字不同返回类型的方法
查看>>
Rails NameError uninitialized constant class solution
查看>>
Android 获取SDCard中某个目录下图片
查看>>
设置cookies第二天0点过期
查看>>
【转载】NIO客户端序列图
查看>>
poj_2709 贪心算法
查看>>
【程序员眼中的统计学(11)】卡方分布的应用
查看>>
文件夹工具类 - FolderUtils
查看>>
http://blog.csdn.net/huang_xw/article/details/7090173
查看>>
lua学习例子
查看>>
研究:印度气候变暖速度加剧 2040年或面临重灾
查看>>