Stack真题

骨骼清奇:
LC 394 Decode String
LC 844 Backspace String Compare
LC 341 Flatten Nested List Iterator

Uber:
LC 636 Exclusive Time of Functions

LC 394 Decode String
s = "3[a2[c]]", return "accaccacc".

class Solution(object):
    def decodeString(self, s):
        stack = []
        stack.append(["", 1])
        #This number 1 here is not used
        num = ""
        for ch in s:
            if ch.isdigit():
                num += ch
            elif ch == '[':
                stack.append(["", int(num)])
                num = ""
            elif ch == ']':
                st, k = stack.pop()
                stack[-1][0] += st*k
            else:
                stack[-1][0] += ch
        return stack[0][0]

LC 844 Backspace String Compare
Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T become "c".

Method one: build string, but space is not O(1)

class Solution(object):
    def backspaceCompare(self, S, T):
        def build(S):
            ans = []
            for c in S:
                if c != '#':
                    ans.append(c)
                elif ans:
                    ans.pop()
            return "".join(ans)
        return build(S) == build(T)

Method 2: reduce function

functools.reduce(func, iter, [initial_value]) cumulatively performs an operation on all the iterable’s elements.

In order to handle below cases, we should set initial value as ""
"a##c"
"#a#c"
Output: True

class Solution(object):
    def backspaceCompare(self, S, T):
        from functools import reduce
        backspace = lambda s,nextc:s[:-1] if nextc=="#" else s+nextc
        return reduce(backspace,S,"")==reduce(backspace,T,"")

Follow up: Can you solve it in O(N) time and O(1) space?
If we do it backward, when we meet a char and we can be sure this char won't be deleted. If we meet a '#', it tell us we need to skip next lowercase char.

class Solution:
    def backspaceCompare(self, S, T):
        si, ti = len(S) - 1, len(T) - 1
        skip_s = skip_t = 0
        
        while si >= 0 or ti >= 0:
            # si stops at non-deleted character in S or -1
            while si >= 0:
                if S[si] == '#':
                    skip_s += 1
                    si -= 1
                elif S[si] != '#' and skip_s > 0:
                    skip_s -= 1
                    si -= 1
                else:
                    break
            
            # ti stops at non-deleted character in T or -1
            while ti >= 0:
                if T[ti] == '#':
                    skip_t += 1
                    ti -= 1
                elif T[ti] != '#' and skip_t > 0:
                    skip_t -= 1
                    ti -= 1
                else:
                    break

            if (ti < 0 and si >= 0) or (si < 0 and ti >= 0):
                # eg. S = "a#", T = "a" 
                return False
            if (ti >= 0 and si >= 0) and S[si] != T[ti]:
                return False
            
            si -= 1
            ti -= 1
        return True

构造一个iterator, 每次yield都是没有被删除的字母!

class Solution(object):
    def backspaceCompare(self, S, T):
        def F(S):
            skip = 0
            for x in reversed(S):
                if x == '#':
                    skip += 1
                elif skip:
                    skip -= 1
                else:
                    yield x

        return all(x == y for x, y in itertools.zip_longest(F(S), F(T)))

LC 341 Flatten Nested List Iterator
Given a nested list of integers, implement an iterator to flatten it.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
NestedInteger有isinteger(), getinteger(),getlist()
Your NestedIterator object will be instantiated and called as such:
i, v = NestedIterator(nestedList), []
while i.hasNext(): v.append(i.next())

LC 636 Exclusive Time of Functions
Given the running logs of n functions that are executed in a nonpreemptive single threaded CPU.

Method 1 : Stack holds the starting time of each function that has been called. We has the elapsed time to the starting time to exclude it from calculation.

def exclusiveTime(self, N, logs):
    ans = [0] * N
    stack = []

    for log in logs:
        fn, typ, time = log.split(':')
        fn, time = int(fn), int(time)

        if typ == 'start':
            stack.append(time)
        else:
            delta = time - stack.pop() + 1
            ans[fn] += delta
            stack = [t+delta for t in stack]

    return ans

Actually, function A only care about the very first function that starts and ends during its own run-time, say they are function B and C. B and C both run during the run time of A respectively. A does not care if there will be function called in B or C. So we can augment our stack to keep track of the raw run time of B and C and that is the time when A does to sleep.

class Solution(object):
    def exclusiveTime(self, n, logs):
        ans = [0] * n
        stack = []
        
        for log in logs:
            fid, state, time = log.split(':')
            fid , time = int(fid),int(time)
            
            if state == 'start':
                stack.append([time, 0])
            else:
                start_time, off_time = stack.pop()
                ans[fid] += time - start_time + 1 - off_time
                if stack:  #already started
                    stack[-1][1] += time - start_time + 1
        return ans
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,386评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,142评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,704评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,702评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,716评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,573评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,314评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,230评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,680评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,873评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,991评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,706评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,329评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,910评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,038评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,158评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,941评论 2 355

推荐阅读更多精彩内容

  • 在喇荣五明佛学院停留了三天,今天早上准备前往亚青寺,虽然只有三百多公里,路不好走加上限速,到了下午四点多才走到甘孜...
    山僧演峰阅读 1,462评论 1 10
  • 这是《春风十里不如你》的Chapter Three,这一章节话题内容讲的是过年。过年对于我们想必并不陌生,然而现在...
    Michael_Lau阅读 285评论 0 3
  • 时间的游戏总有些东西记得又有很多忘记 高冷的学府铁门紧闭只有春风荡起的绿意透过高墙隐约轻摇在风里 一个洁净的少女白...
    阿喜玛雅阅读 280评论 8 15