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

構(gòu)造一個(gè)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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末闯割,一起剝皮案震驚了整個(gè)濱河市竿拆,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌鼓黔,老刑警劉巖不见,帶你破解...
    沈念sama閱讀 217,509評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件崔步,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡井濒,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門酪惭,熙熙樓的掌柜王于貴愁眉苦臉地迎上來者甲,“玉大人,你說我怎么就攤上這事∧凼担” “怎么了窥岩?”我有些...
    開封第一講書人閱讀 163,875評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長颂翼。 經(jīng)常有香客問我,道長球及,這世上最難降的妖魔是什么集歇? 我笑而不...
    開封第一講書人閱讀 58,441評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮诲宇,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘鹅心。我一直安慰自己纺荧,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,488評(píng)論 6 392
  • 文/花漫 我一把揭開白布宙暇。 她就那樣靜靜地躺著,像睡著了一般桃熄。 火紅的嫁衣襯著肌膚如雪型奥。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,365評(píng)論 1 302
  • 那天厢汹,我揣著相機(jī)與錄音,去河邊找鬼界弧。 笑死,一個(gè)胖子當(dāng)著我的面吹牛夹纫,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播舰讹,決...
    沈念sama閱讀 40,190評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼月匣,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了锄开?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,062評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤头遭,失蹤者是張志新(化名)和其女友劉穎癣诱,沒想到半個(gè)月后计维,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體撕予,經(jīng)...
    沈念sama閱讀 45,500評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡实抡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,706評(píng)論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了吆寨。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,834評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡猜敢,死狀恐怖盒延,靈堂內(nèi)的尸體忽然破棺而出鼠冕,到底是詐尸還是另有隱情添寺,我是刑警寧澤懈费,帶...
    沈念sama閱讀 35,559評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站票罐,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏该押。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,167評(píng)論 3 328
  • 文/蒙蒙 一烟具、第九天 我趴在偏房一處隱蔽的房頂上張望奠蹬。 院中可真熱鬧,春花似錦囤躁、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,779評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽猜极。三九已至消玄,卻和暖如春跟伏,著一層夾襖步出監(jiān)牢的瞬間翩瓜,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,912評(píng)論 1 269
  • 我被黑心中介騙來泰國打工勘高, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留坟桅,地道東北人华望。 一個(gè)月前我還...
    沈念sama閱讀 47,958評(píng)論 2 370
  • 正文 我出身青樓赖舟,卻偏偏與公主長得像,于是被迫代替她去往敵國和親宾抓。 傳聞我的和親對(duì)象是個(gè)殘疾皇子子漩,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,779評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • 在喇榮五明佛學(xué)院停留了三天幢泼,今天早上準(zhǔn)備前往亞青寺讲衫,雖然只有三百多公里,路不好走加上限速焦人,到了下午四點(diǎn)多才走到甘孜...
    山僧演峰閱讀 1,462評(píng)論 1 10
  • 這是《春風(fēng)十里不如你》的Chapter Three,這一章節(jié)話題內(nèi)容講的是過年忽匈。過年對(duì)于我們想必并不陌生,然而現(xiàn)在...
    Michael_Lau閱讀 285評(píng)論 0 3
  • 時(shí)間的游戲總有些東西記得又有很多忘記 高冷的學(xué)府鐵門緊閉只有春風(fēng)蕩起的綠意透過高墻隱約輕搖在風(fēng)里 一個(gè)潔凈的少女白...
    阿喜瑪雅閱讀 280評(píng)論 8 15