1. 程式人生 > 其它 >【Lintcode】263. Matching of Parentheses

【Lintcode】263. Matching of Parentheses

技術標籤:# 陣列、連結串列與模擬資料結構演算法字串

題目地址:

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)