[LeetCode] 20. Valid Parentheses

本文详细解析了如何通过栈来实现括号匹配的有效性检查,包括C++与Java两种语言的具体实现方式,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:https://leetcode.com/problems/valid-parentheses/description/

题目

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 all valid but "(]" and "([)]" are not.

思路

需要后进先出来做匹配,用栈非常合适。
class Solution {
public:
    bool isValid(string s) {
        std::stack<char>  chstack;
        for(int i = 0 ;i<s.length();i++){
            if(s[i]=='('||s[i]=='{'||s[i]=='[') chstack.push(s[i]);
            else{
                if(chstack.empty()) return false;
                char chtmp = chstack.top();
                chstack.pop();
                switch(chtmp){   
                        case '(':{
                            if(s[i]==')')   continue;
                            else    return false;
                            break;   
                        }
                        
                        case '{':{
                            if(s[i]=='}')   continue;
                            else    return false;
                            break; 
                        }
                        case '[':{
                            if(s[i]==']')   continue;
                            else    return false;
                            break; 
                        }
                }

            }
        }
        if(!chstack.empty()) return false;
        return true;
    }
};


1.栈的使用
声明:std::stack<char>  stack;
操作:添加 stack.push();是否为空stack.empty();取top:stack.top();删除top:stack.pop();
2.switch-case
switch(char){
case 'a':{
cout<<char<<endl;
break;
}
}

JAVA


class Solution {
    public boolean isValid(String s) {
        Stack<Character> chstack = new Stack<Character>();
        for(char c : s.toCharArray()){
            if(c=='(')  chstack.push(')');
            else if(c=='{') chstack.push('}');
            else if(c=='[') chstack.push(']');
            else if(chstack.isEmpty()||chstack.pop()!=c)  return false;
        }
        return chstack.isEmpty();
    }
}
语法:
1.栈的使用:
声明:
Stack<Character> chstack = new Stack<Character>();
其中<>中应为对象,而char为内置数据类型,所以需要使用 Character 类型,可以和char 用'=='比较,用'='赋值。
操作:
添加:chstack.push();
取top并删除:chstack.pop();

class Solution {
    public boolean isValid(String s) {
        Stack<Character> chstack = new Stack<Character>();
        for(char c : s.toCharArray()){
            switch(c){
                case '(':
                    chstack.push(')');
                    break;
                case '{':
                    chstack.push('}');
                    break;
                case '[':
                    chstack.push(']');
                    break;
                default:
                    if(chstack.isEmpty()||chstack.pop()!=c)  return false;
            }
        }
        return chstack.isEmpty();
    }
}
语法:
2.switch-case
switch(c){
case '{':
pass;
break;
default:
pass;
break;
}
为了编写一个判断输入字符串是否为四则运算表达式的程序,我们可以使用LL(1)文法,它是一种左递归的文法,通常用于描述简单语言结构,如数学表达式。这里是一个简化的LL(1)解析器的示例,我们将使用Python的正则表达式库`re`来完成词法分析,并结合简单的语法规则来检查。 ```python import re # 定义词法规则 def is_valid_token(token): # 判断基本运算符、数字和变量 operators = ['+', '-', '*', '/'] numbers = r'\d+' variables = r'[a-zA-Z_]+' if token in operators or token.isdigit() or re.match(variables, token): return True else: return False def lexer(input_string): tokens = re.findall(r'(?:\d+|[-+*/]|[a-zA-Z_]+)', input_string) return [token for token in tokens if is_valid_token(token)] def check_LL1(parsed_tokens): stack = [] operators = {'+': 1, '-': 1, '*': 2, '/': 2} # 操作数优先级 for token in parsed_tokens: if token.isdigit(): stack.append(int(token)) elif token in operators: while stack and stack[-1] != '(' and operators[token] <= operators.get(stack[-1], 0): yield f"Invalid syntax: {stack.pop()} should be evaluated before {token}" stack.append(token) elif token == ')': while stack[-1] != '(': yield f"Mismatched parentheses: {stack.pop()}" stack.pop() else: yield f"Illegal character: {token}" if stack: yield f"Incomplete expression: missing closing parenthesis" # 使用示例 expression = "3 + 4 * (5 - 6)" tokens = lexer(expression) for error in check_LL1(tokens): print(error)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值