题目描述:括号(小括号、中括号、大括号)的匹配
传送门:https://leetcode-cn.com/problems/valid-parentheses/
解法:《数据结构》中作为例子引出栈的概念。用一个栈维护,从左到右扫描目标字符串,如果括号匹配,即满足三种情况:
①、s[i] == ‘)‘ && Stack.top() == ‘(‘
②、s[i] == ‘]‘ && Stack.top() == ‘[‘
③、s[i] == ‘}‘ && Stack.top() == ‘{‘
如果括号不匹配,就把当前字符压入栈中。扫描完目标字符串后,观察栈中是否还有元素,如果存在,则不是有效字符串。
class Solution { public: bool isValid(string s) { stack<char> Stack; int len = s.length(); for(int i = 0; i < len; i ++ ){ if (Stack.empty()) { Stack.push(s[i]); continue; } else if (s[i] == ‘)‘ && Stack.top() == ‘(‘){ Stack.pop(); continue; } else if (s[i] == ‘]‘ && Stack.top() == ‘[‘){ Stack.pop(); continue; } else if (s[i] == ‘}‘ && Stack.top() == ‘{‘){ Stack.pop(); continue; } else{ Stack.push(s[i]); //括号不匹配而 } } if (!Stack.empty()) return false; return true; } };
原文地址:https://www.cnblogs.com/xiazhenbin/p/12188796.html
时间: 2024-11-04 04:27:46