leetcode:判断给定的字符串括号是否有效

本文介绍了如何使用Go语言和C++解决LeetCode中的有效括号问题,通过栈数据结构来检查给定字符串中的括号是否匹配。
摘要由CSDN通过智能技术生成
Given a string containing just the characters'(',')','{',
'}','['and']',determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed by in the correct order.
Note that an empty string is also considered valid;

Example 1:
Input:"()"
Output:true

Example 2:
Input:"()[]"
Output:true

Example 3:
Input:"(]"
Output:false

Example 4:
Input:"([)]"
Output:false

解题思路:
这道题是典型的括号问题.可以通过栈的思路解决,遇到左括号就进栈,遇到右
括号就应当与栈顶元素对应的是左括号,然后栈顶元素出栈.最后看栈顶元素
是否还有其他元素,如果为空,即匹配.此外若为空字符也满足括号匹配.

Go语言实现

package main

import "fmt"

func IsValid(str string)bool{
	/*空字符串直接返回*/
	if len(str)==0{
		return true
	}
	stack:=make([]rune,0)
	for _,v:=range str{
		if (v=='[')||(v=='(')||(v=='{'){
			stack=append(stack,v)
		}else if (v==']'&&len(stack)>0&&stack[len(stack)-1]=='[')||
			(v==')'&&len(stack)>0&&stack[len(stack)-1]=='(')||
			(v=='}'&&len(stack)>0&&stack[len(stack)-1]=='{'){
			stack=stack[:len(stack)-1]
		}else{
			return false
		}
	}
	return len(stack)==0
}
func main(){
	fmt.Println("判断括号是否有效")
	str:="([)]"
	fmt.Println(IsValid(str))
}

C++语言实现

#include <iostream>
#include <stack>

using namespace std;

class Solution{
public:
    bool IsValid(string str){
        if(str.empty()){
            return true;
        }
        stack<char> ans;
        for(auto& i:str){
            if(i=='['||i=='('||i=='{'){
                ans.push(i);
            }else if((i==']'&&ans.size()>0&&ans.top()=='[')
            ||(i==')'&&ans.size()>0&&ans.top()=='(')
            ||(i=='}'&&ans.size()>0&&ans.top()=='{')){
                ans.pop();
            }else{
                return false;
            }
        }
        return ans.size()==0;
    }
};

int main(int argc,char* argv[]){
    string str="([])";
    cout<<Solution().IsValid(str)<<endl;
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路上的追梦人

您的鼓励就是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值