Easy!
題目描述:
給定一個只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判斷字符串是否有效。
有效字符串需滿足:
- 左括號必須用相同類型的右括號閉合。
- 左括號必須以正確的順序閉合。
注意空字符串可被認為是有效字符串。
示例 1:
輸入: "()" 輸出: true
示例 2:
輸入: "()[]{}" 輸出: true
示例 3:
輸入: "(]" 輸出: false
示例 4:
輸入: "([)]" 輸出: false
示例 5:
輸入: "{[]}" 輸出: true
解題思路:
這道題讓我們驗證輸入的字符串是否為括號字符串,包括大括號,中括號和小括號。這里我們需要用一個棧,我們開始遍歷輸入字符串,如果當前字符為左半邊括號時,則將其壓入棧中,如果遇到右半邊括號時,若此時棧為空,則直接返回false,如不為空,則取出棧頂元素,若為對應的左半邊括號,則繼續循環,反之返回false,
C++代碼:
1 class Solution { 2 public: 3 bool isValid(string s) { 4 stack<char> parentheses; 5 for (int i = 0; i < s.size(); ++i) { 6 if (s[i] == '(' || s[i] == '[' || s[i] == '{') parentheses.push(s[i]); 7 else { 8 if (parentheses.empty()) return false; 9 if (s[i] == ')' && parentheses.top() != '(') return false; 10 if (s[i] == ']' && parentheses.top() != '[') return false; 11 if (s[i] == '}' && parentheses.top() != '{') return false; 12 parentheses.pop(); 13 } 14 } 15 return parentheses.empty(); 16 } 17 };