leetcode 224 括號匹配

2021-10-21 16:57:05 字數 2821 閱讀 4946

此題準確的說是乙個括號匹配問題,我們可以從裡到外拆解問題。每遇到乙個後括號,就把前面的提出來解決,這樣就沒有內層了,可以用棧實現,**如下:

class

solution

:def

calculate

(self, s:

str)

->

int:

iflen

(s)==0:

return

0 stack =

defprocess()

: l =

last, tmp, pos =

's',0,

0while stack:

c0 = stack.pop()if

type

(c0)

==type

('2'

)and c0.isdigit(

): c0 =

int(c0)

if c0 ==

'(':

break

elif

type

(c0)

==type(2

):tmp +=

10**pos*c0

pos +=

1else

: tmp, pos =0,

0 num =

0 sign =

1# 1為加,-1為減

for c1 in

reversed

(l):

iftype

(c1)

==type(2

):num += sign*

int(c1)

elif c1 ==

'-':

sign =-1

elif c1 ==

'+':

sign =

1for i, c in

enumerate

(s):

if c ==

')':

process(

)elif c !=

' ':

process(

)return stack[

0]

可以看到,中間有一步是很浪費時間的,就是把元素取出來,又放入新的列表,又取出來。如果能省去這一過程,程式會快很多。

class

solution

:def

calculate

(self, s:

str)

->

int:

iflen

(s)==0:

return

0 stack =

defprocess()

: num =

0 last, tmp, pos =

's',0,

0while stack:

c0 = stack.pop()if

type

(c0)

==type

('2'

)and c0.isdigit(

): c0 =

int(c0)

if c0 ==

'(':

break

elif

type

(c0)

==type(2

):tmp +=

10**pos*c0

pos +=

1else

:if c0 ==

'-': tmp =

-tmp

num += tmp

tmp, pos =0,

0for i, c in

enumerate

(s):

if c ==

')':

process(

)elif c !=

' ':

process(

)return stack[

0]

其實這樣還是很慢,所以我們必須找到更透徹的解法:即題解解法,所有數字沒有變,變的只是符號,我們只需要用乙個棧存符號即可。。這樣就會很快。

此外,從前往後累加乙個數也挺簡單的,一直讓前面乘10即可。

class

solution

:def

calculate

(self, s:

str)

->

int:

iflen

(s)==0:

return

0 stack =[1

] ret, sign =0,

1 tmp =

0for i, c in

enumerate

(s):

if c.isdigit():

tmp = tmp*10+

int(c)

else

: ret += tmp*sign

tmp =

0if c ==

'+':

sign = stack[-1

]elif c ==

'-':

sign =

-stack[-1

]elif c ==

'(':

elif c ==

')':

stack.pop(

)return ret+tmp*sign

leetcode 224 基本計算器

題目 基本計算器 實現乙個基本的計算器來計算乙個簡單的字串表示式的值。字串表示式可以包含左括號 右括號 加號 減號 非負整數和空格 示例1 輸入 1 1 輸出 2 示例2 輸入 2 1 2 輸出 3 示例3 輸入 1 4 5 2 3 6 8 輸出 23 說明 c include include cl...

leetcode 224 基本計算器

實現乙個基本的計算器來計算乙個簡單的字串表示式的值。字串表示式可以包含左括號 右括號 加號 減號 非負整數和空格 示例 1 輸入 1 1 輸出 2 示例 2 輸入 2 1 2 輸出 3 示例 3 輸入 1 4 5 2 3 6 8 輸出 23 採用雙棧法,設立乙個資料棧和乙個操作符棧,在遍歷字串的過程...

Leetcode 224基本計算器

邏輯先寫第三步再寫第二步,思考時要按照表示式順序先看數字再看右括號正常考慮,時間複雜度o n class solution intcalculate string s else 遇到數字 nums.push n 處理多位數等價寫法 while j s.size isdigit s j j j i c...