有效的括号(C++编写)

阅读: 评论:0

有效的括号(C++编写)

有效的括号(C++编写)

题目描述:
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

示例 1:
输入: “()”
输出: true

示例 2:
输入: “()[]{}”
输出: true

示例 3:
输入: “(]”
输出: false

示例 4:
输入: “([)]”
输出: false

示例 5:
输入: “{[]}”
输出: true

解题思路:
这道题的主要知识点是考栈操作。
首先大家可以先把第一个符号为 ’ ) ‘,’ ] ‘,’ } ',的这种情况直接返回false,而输入的字符如果为奇数的话这种情况也可以返回false。
剩下的情况就是字符长度为偶数,并且第一位不是上述讲的那三种符号的情况了,以下是代码块,这边的话我建议大家把这两种都自己写一下:

(1)直接调用栈操作:

#include<iostream>
#include<stack>
#include<string>
using namespace std;
class Solution
{public:int isValid(string s){stack<char> str;int length = s.length();if(s[0]==')'||s[0]=='}'||s[0]==']'||length%2==1){cout<<"false";return 0;}for(int i=0;i<length;i++){if(s[i]=='('||s[i]=='{'||s[i]=='[')str.push(s[i]);if(s[i]==')'||s[i]==']'||s[i]=='}'){char temp = p();str.pop(); //删除栈顶元素if(temp=='('&&s[i]==')'||temp=='{'&&s[i]=='}'||temp=='['&&s[i]==']')continue;   //注意此处不能直接cout<<"true"else{cout<<"false";return 0;}}}pty())cout<<"true";}
};
int main()
{Solution su;su.isValid("])");
}

(2)自己写栈的各种操作:

#include<iostream>
#include<string>
#define MAXSIZE 100
using namespace std;typedef struct
{char *base,*top;int stacksize;
}Stack;void InitStack(Stack &S)
{S.base = new char[MAXSIZE];S.top = S.base;S.stacksize = MAXSIZE;
}void PushStack(Stack &S,string sg) 
{int i=0;*S.top = sg[i];+&#p;
}int isEmptyStack(Stack S)  
{p - S.base==0){//cout<<"empty"<<endl;return 1;}elsereturn 0;
}int getTopStack(Stack &S) 
{--S.top;return *S.top;}
int main()
{string st;Stack str;cin>>st;int len = st.length();InitStack(str);if(st[0]==')'||st[0]==']'||st[0]=='}'||len%2==1){cout<<"false"<<endl;return 0;}for(int i=0;i<len;i++){if(st[i]=='('||st[i]=='{'||st[i]=='['){string s;s = st[i];PushStack(str,s);}if(st[i]==')'||st[i]=='}'||st[i]==']'){char temp = getTopStack(str);if(temp=='['&&st[i]==']'||temp=='('&&st[i]==')'||temp=='{'&&st[i]=='}')continue;else{cout<<"false"<<endl;return 0;}}}if(isEmptyStack(str)==1){cout<<"true"<<endl;return 0;}}

有什么错误和不足的地方欢迎大家指出!

本文发布于:2024-02-01 09:36:30,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170675138935701.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

上一篇:centos7配网卡
下一篇:JS有效的括号
标签:括号
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23