Uva 673 Parentheses Balance

简介: 点击打开链接 解题思路:我们知道括号如果要完全匹配,那么左括号数等于右括号数,那么我们可以用一个栈来做,遇到左括号(“(” ,“]”)就压入,如果下一个符号刚好为栈顶元素那么就清除栈顶元素 注意:如果遇到最后只有一个括号,那么只能入栈。

点击打开链接


解题思路:我们知道括号如果要完全匹配,那么左括号数等于右括号数,那么我们可以用一个栈来做,遇到左括号(“(” ,“]”)就压入,如果下一个符号刚好为栈顶元素那么就清除栈顶元素


注意:如果遇到最后只有一个括号,那么只能入栈。还有数据中会有空格出现,要用gets输入,不要用scanf。


代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
void output(char *str){
    int i;
    stack<char>s;//建立一个空栈
    for(i = 0 ; i < strlen(str) ; i++){
        if(str[i] == ' ')//如果是空格直接跳过
            continue;
        if(str[i] == '(' || str[i] == '[' || s.size() == 0)//如果是左括号或当前的栈为空则要压入该元素
            s.push(str[i]);

        //如果遇到右括号则判断是否栈顶的元素和当前括号匹配,如果匹配就删除栈顶元素,否则入栈
        if(str[i] == ')'){
            if(s.top() == '(')
                s.pop();
            else
                s.push(str[i]);
        }
        if(str[i] == ']'){
            if(s.top() == '[')
                s.pop();
            else
                s.push(str[i]);
        }
    }

   //最后判断栈是否为空,空则输出Yes,否则输出No。

   if(s.empty())
        cout<<"Yes\n";
    else
        cout<<"No\n";
}
int main(){
    int i , j;
    int n;
    char ch[150];
    while(scanf("%d" , &n) != EOF){
        getchar();
        for(i = 1 ; i <= n ; i++){
            gets(ch);
            output(ch);   
        }
    }
    return 0;
}






目录
相关文章
|
9月前
uva673 Parentheses Balance
uva673 Parentheses Balance
31 0
|
canal
LeetCode 125. Valid Palindrome
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
67 0
LeetCode 125. Valid Palindrome
LeetCode 241. Different Ways to Add Parentheses
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。
55 0
LeetCode 241. Different Ways to Add Parentheses
Leetcode-Easy 20. Valid Parentheses
Leetcode-Easy 20. Valid Parentheses
90 0
Leetcode-Easy 20. Valid Parentheses
|
机器学习/深度学习
[LeetCode]--22. Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: [ "((()))", "(()())", "(())()",
1083 0
[LeetCode]--20. Valid Parentheses
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid. The brackets must close in the correct order, “()” and “()[]{}” are a
1268 0