📟作者主頁:慢熱的陜西人
🌴專欄鏈接:力扣刷題日記
📣歡迎各位大佬👍點贊🔥關注🚓收藏,🍉留言
文章目錄
- 牛客熱題:有效括號
- 題目鏈接
- 方法一:棧
- 思路
- 代碼
- 復雜度
牛客熱題:有效括號
題目鏈接
有效括號序列_牛客題霸_牛客網 (nowcoder.com)
方法一:棧
思路
入棧:
- 當棧內為空或者棧頂的括號和當前遍歷到的括號是不匹配的
出棧:
- 當棧頂的括號和當前遍歷到的括號是匹配的情況
代碼
stack<char> st;bool check(const char c){if(c == ')' && st.top() == '(') return true;else if(c == ']' && st.top() == '[') return true;else if(c == '}' && st.top() == '{') return true;else return false;}bool isValid(string s) {for(auto c : s){if(!st.empty()){if(!check(c)) st.push(c);else st.pop();}else{st.push(c);} }return st.empty();}
復雜度
時間復雜度:O(N) ,遍歷了一遍string
空間復雜度:O(N), 創建了一個棧空間,用于臨時存儲括號