【Lintcode】263. Matching of Parentheses
阿新 • • 發佈:2021-01-04
題目地址:
https://www.lintcode.com/problem/matching-of-parentheses/description
給定一個長 n n n的小括號序列,判斷其是否合法。
括號序列合法的充要條件是,任意字首中左括號數量一定大於等於右括號數量,並且整個序列左右括號數量相等。程式碼如下:
public class Solution {
/**
* @param string: A string
* @return: whether the string is a valid parentheses
*/
public boolean matchParentheses(String string) {
// write your code here
if (string.length() % 2 != 0) {
return false;
}
int l = 0, r = 0;
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) == '(') {
l++ ;
} else {
r++;
}
if (l < r) {
return false;
}
}
return l == r;
}
}
時間複雜度 O ( n ) O(n) O(n),空間 O ( 1 ) O(1) O(1)。