【leetcode刷题】71 simplify path

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

解题思路
这道题有两种解法,一种是用栈;另一种是用split函数


  • 栈的思想:
    遍历path中的每一个字符,遇到’/‘不管,继续遍历,遇到不是’/‘的,开始记录字符,直到出现下一个’/’
    检查这一段字符,如果是’.’,不入栈;如果是’…‘且栈不为空,pop出最后一个元素;其他情况,字符串入栈
    检查完毕后,用join函数把所有字符串用’/'连接起来输出

  • split方法
    用split(’/’)分割path中的元素
    遍历元素:如果出现’‘和’.’,删除当前元素;如果出现’…'且不是第一个元素,删除上一个元素;否则继续往下遍历
    检查完毕后依然用join函数连接

代码

# 栈
class Solution(object):
    def simplifyPath(self, path):
        """
        :type path: str
        :rtype: str
        """
        i = 0
        cur = ''
        ans_list = []
        ans = '/'
        while i<len(path):
            start = i
            while path[start]=='/':
                start += 1
                if start==len(path):
                    break
            if start==len(path):
                break
            i = start
            while path[i] != '/':
                cur += path[i]
                i += 1
                if i==len(path):
                    break
            if cur=='.':
                cur = ''
                continue
            elif cur=='..':
                if ans_list:
                    ans_list.pop()
                cur = ''
                continue
            ans_list.append(cur)
            cur = ''
        ans += '/'.join(item for item in ans_list)
        return ans
# split函数
class Solution(object):
    def simplifyPath(self, path):
        """
        :type path: str
        :rtype: str
        """
        can_path = path.split('/')
        ans = '/'
        i = 0
        while i<len(can_path):
            if not can_path[i] or can_path[i]=='.':
                del can_path[i]
                continue
            if can_path[i]=='..':
                if i==0:
                    can_path[i] = ''
                else:
                    can_path.pop(i)
                    can_path.pop(i-1)
                    if i-1>=0:
                        i -= 1
                    else:
                        i = 0
                continue
            i += 1
        ans += '/'.join(item for item in can_path)

        return ans

参考链接
https://www.cnblogs.com/zuoyuan/p/3777289.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值