模拟专题 - leetcode481. Magical String/71. Simplify Path★

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a786150017/article/details/83153495

481. Magical String

题目描述

给定正整数N,返回神奇字符串S中前N个数字中的’1’。

例子

Input: 6
Output: 3

Explanation: The first 6 elements of magical string S is “12211” and it contains three 1’s, so return 3.

思想
可以根据原始S的结果和统计连续1,2的结果,相互推导
需要一个列表存储结果,需要一个指针指示当前group的位置
解法

class Solution(object):
    def magicalString(self, n):
        """
        :type n: int
        :rtype: int
        """
        arr = [1,2,2]
        idx = 2
        while len(arr) < n:
            arr += [3 - arr[-1]] * arr[idx]  # arr[idx]个
            idx += 1
        return arr[:n].count(1)

71. Simplify Path

题目描述

给定绝对路径,简化路径

例子

path = “/home/”, => “/home”
path = “/a/./b/…/…/c/”, => “/c”
path = “/a/…/…/b/…/c//.//”, => “/c”
path = “/a//b////c/d//././/…”, => “/a/b/c”

unix系统风格下,".“表示当前目录,可以忽略;”…"表示上级目录

扫描二维码关注公众号,回复: 3662270 查看本文章

思想

有效字符入栈,遇到…就弹出一个栈顶元素,遇到.就无视。
特殊情况 - /…/

解法

class Solution(object):
    def simplifyPath(self, path):
        """
        :type path: str
        :rtype: str
        """
        stack = []
        path = path.split('/')
        for ss in path:
            if ss:  # 注意ss非空
                if ss == '..':
                    if stack:
                        stack.pop()
                elif ss != '.':    
                    stack.append(ss)
        return '/' + '/'.join(stack)

猜你喜欢

转载自blog.csdn.net/a786150017/article/details/83153495