Leetcode挑戰: Day06 valid parentheses

leetcode

為了加強自己的程式能力,因此記錄每天刷leetcode的解法+說明,今天會用RubyPythonJavaScript來解題,今天來到第六天,讓我們繼續吧!

題目來源:leetcode

Ruby

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def is_valid(s)
stack = []
mapping = { ')' => '(', '}' => '{', ']' => '[' }

s.each_char do |char|
if mapping.key?(char)
top_element = stack.pop || '#'
return false if mapping[char] != top_element
else
stack.push(char)
end
end

stack.empty?
end

先設定一個名為stack的空陣列,還有左括號的hash,
因為key為右括號,所以第一次的左括號都無懸念地進入stack,第二次迴圈,top_element則取出上一次放進去的左括號,並去比對是否和第二次迴圈對應到的左括號相符。

如果不符合即會回傳false,如果所有的括號都成對,即stack為空

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def isValid(self, s: str) -> bool:
stack = []
mapping = {')': '(', '}': '{', ']': '['}

for char in s:
if char in mapping:
top_element = stack.pop() if stack else '#'
if mapping[char] != top_element:
return False
else:
stack.append(char)

return not stack

python使用一樣的方式,不過因為python的添加list使用的是append,所以這裡我改用stack.append(char)

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var isValid = function(s) {
const stack = [];
const mapping = { ')': '(', '}': '{', ']': '[' };

for (const char of s) {
if (mapping[char]) {
const topElement = stack.pop() || '#';
if (mapping[char] !== topElement) {
return false;
}
} else {
stack.push(char);
}
}

return !stack.length;
};

JS也是依樣畫葫蘆!只要稍微改寫一下寫法即可

參考資料:
Python手冊

评论