LeetCode 20.有效的括號 題解
阿新 • • 發佈:2021-12-06
題目
給定一個只包括 '(',')','{','}','[',']'的字串 s ,判斷字串是否有效。
有效字串需滿足:
- 左括號必須用相同型別的右括號閉合。
- 左括號必須以正確的順序閉合。
示例 1:
輸入:s = "()" 輸出:true
思路
當出現右括號時,如'(','{','[‘ 必定需要物件的左括號,才能時是個閉合的字串
程式碼
public bool IsValid(string s) { List<char> ayyayC = new List<char>(); foreach(char c in s) { if (c == '(' || c == '{' || c == '[') { ayyayC.Add(c); } else { if(ayyayC.Count == 0) return false; if (leftParentheses(ayyayC[ayyayC.Count - 1]) == rightParentheses(c)) { ayyayC.RemoveAt(ayyayC.Count - 1); } else { return false; } } } if (ayyayC.Count == 0) return true; return false; } public int leftParentheses(char c) { switch (c) { case '(': return 1; case '{' : return 2; case '[': return 3; default: return 0; } } public int rightParentheses(char c) { switch (c) { case ')': return 1; case '}' : return 2; case ']': return 3; default: return 0; } }