日期:2026年9月28日
LeetCode 題目連結:1614. Maximum Nesting Depth of the Parentheses
解題想法
簡單題。題目給一個字串 $s$,長度為 1 到 100,內容只有數字 0 到 9、+-*/(),計算括號的最大深度。雖然看起來字串內容很複雜,但實際上只要數括號數量即可,不需要管算式內容。假設左括號數量為 $left$、最大深度為 $imax$,用一個 for 迴圈依序讀取字串的字元 $c$,如果 $c$ 是 (,$left$ 加 1,更新 $imax$;如果 $c$ 是 ),$left$ 減 1。
Python 程式碼
Runtime: 0 ms, beats 100.00%. Memory: 19.24 MB, beats 50.40%.
class Solution:
def maxDepth(self, s: str) -> int:
left, imax = 0, 0
for c in s:
if c == '(':
left += 1
imax = max(imax, left)
elif c == ')':
left -= 1
return imax
C++ 程式碼
Runtime: 0 ms, beats 100.00%. Memory: 8.42 MB, beats 24.11%.
class Solution {
public:
int maxDepth(string s) {
int left = 0, imax = 0;
for(char c : s) {
if (c == '(') {
left++;
imax = max(imax, left);
} else if (c == ')') {
left--;
}
}
return imax;
}
};
C 語言程式碼
Runtime: 0 ms, beats 100.00%. Memory: 8.72 MB, beats 13.45%.
#define max(a, b) ((a) > (b) ? (a) : (b))
int maxDepth(char* s) {
int n = strlen(s), left = 0, imax = 0;
for(int i = 0; i < n; i++) {
if (s[i] == '(') {
left++;
imax = max(imax, left);
} else if (s[i] == ')') {
left--;
}
}
return imax;
}
沒有留言:
張貼留言