【力扣】括号匹配(栈的应用)
题目描述
顾名思义
代码如下:
#include<iostream>
#include<string>
#include<stack>
using namespace std;
bool isValid(string s){
	if(s.empty()){
		return true;
	}
	if(s.size()%2 != 0){
		return false;
	}
	int i = 0;
	stack<char> st;
	while(i < s.size()){
		if(s[i] == '('){
			st.push(')');
			//continue;
		}
		if(s[i] == '['){
			st.push(']');
			//continue;
		}
		if(s[i] == '{'){
			st.push('}');
			//continue;
		}
		if(s[i] == ')' || s[i] == ']' || s[i] == '}'){
			if(st.empty()){
				return false;
			}
			if(st.top() == s[i]){
				st.pop();
			}else{
				return false;
			}
			
		}
		i++;
	}
	return st.empty();
} 
//bool isValid(string s) {
//        if (s.size() % 2 != 0) return false; // 如果s的长度为奇数,一定不符合要求
//        stack<char> st;
//        for (int i = 0; i < s.size(); i++) {
//            if (s[i] == '(') st.push(')');
//            else if (s[i] == '{') st.push('}');
//            else if (s[i] == '[') st.push(']');
//            // 第三种情况:遍历字符串匹配的过程中,栈已经为空了,没有匹配的字符了,说明右括号没有找到对应的左括号 return false
//            // 第二种情况:遍历字符串匹配的过程中,发现栈里没有我们要匹配的字符。所以return false
//            else if (st.empty() || st.top() != s[i]) return false;
//            else st.pop(); // st.top() 与 s[i]相等,栈弹出元素
//        }
//        // 第一种情况:此时我们已经遍历完了字符串,但是栈不为空,说明有相应的左括号没有右括号来匹配,所以return false,否则就return true
//        return st.empty();
//    }
int main(){
	string s;
	cin>>s;
	if(isValid(s)){
		cout<<"true";
	}else{
		cout<<"false";
	}
	return 0;
}
里面那个遇到左括号入栈右括号的小技巧很有意思。

                
            
        
浙公网安备 33010602011771号