判断字符串中的括号是否匹配——c和c++实现
判斷字符串中的括號是否匹配
遞歸實現:?
先檢搜一對匹配的括號,再對里面的內容進行匹配,匹配完后再繼續往下匹配……?
代碼如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 在start與end中搜索匹配?
int fun(char *str, int start, int end)
{
? ? char chLeft; ? ? ? ?// 左括號
? ? char chRight; ? ? ? // 右括號
? ? while((start<=end) && (str[start] != '\0'))
? ? {
? ? ? ? switch(str[start])
? ? ? ? {
? ? ? ? ? ? case '(':
? ? ? ? ? ? ? ? chLeft = str[start];
? ? ? ? ? ? ? ? chRight = ')';
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? case '[':
? ? ? ? ? ? ? ? chLeft = str[start];
? ? ? ? ? ? ? ? chRight = ']';
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? case '{':
? ? ? ? ? ? ? ? chLeft = str[start];
? ? ? ? ? ? ? ? chRight = '}';
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? case ')':
? ? ? ? ? ? case ']':
? ? ? ? ? ? case '}':
? ? ? ? ? ? ? ? return 0;
? ? ? ? ? ? default:
? ? ? ? ? ? ? ? chLeft = '\0';
? ? ? ? ? ? ? ? break;
? ? ? ? }
? ? ? ? if(str[start] == chLeft)
? ? ? ? {
? ? ? ? ? ? int a = 1;
? ? ? ? ? ? int b=0;
? ? ? ? ? ? int t = start+1;
? ? ? ? ? ? while((t<=end) && (str[t] != '\0')) // 搜索匹配的右括號?
? ? ? ? ? ? {
? ? ? ? ? ? ? ? if(str[t] == chLeft)
? ? ? ? ? ? ? ? ? ? ++a;
? ? ? ? ? ? ? ? if(str[t] == chRight)
? ? ? ? ? ? ? ? ? ? ++b;
? ? ? ? ? ? ? ? if(b>a)
? ? ? ? ? ? ? ? ? ? return 0;
? ? ? ? ? ? ? ? if(a == b) ? ? ?// 再對匹配括號里面的括號進行匹配?
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? if(0 == fun(str, start+1, t-1)) // 遞歸調用?
? ? ? ? ? ? ? ? ? ? ? ? return 0;
? ? ? ? ? ? ? ? ? ? start=t;
? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ++t;
? ? ? ? ? ? }
? ? ? ? ? ? if(a>b)
? ? ? ? ? ? ? ? return 0;
? ? ? ? }
? ? ? ? ++start;
? ? }
? ? return 1;
}
int main(void){
? ? char str[1024];
? ? gets(str);
? ? int length = strlen(str);
? ? int i = fun(str, 0, length-1);
? ? if(i == 1){
? ? ? ? printf("括號匹配!\n");
? ? }else{
? ? ? ? printf("括號不匹配!\n");
? ? }
? ? return 0;
}
C++實現如下:
#include <iostream>
#include <cstring>
#include <stack>
?
using namespace std;
?
int main()
{
? ? stack<char>a;
? ? int flag=1,i;
? ? char ch[100];
? ? cin>>ch;
? ? for(i=0;i<strlen(ch);i++){
? ? ? ? if(ch[i]=='{'||ch[i]=='('||ch[i]=='[')
? ? ? ? ? ? a.push(ch[i]);
? ? ? ? else{
? ? ? ? ? ? if(a.empty()==true){
? ? ? ? ? ? ? ? flag=0;
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? }
? ? ? ? ? ? else if((ch[i]=='}'&&a.top()=='{')||(ch[i]==')'&&a.top()=='(')||(ch[i]==']'&&a.top()=='['))
? ? ? ? ? ? ? ? a.pop();
? ? ? ? ? ? else{
? ? ? ? ? ? ? ? flag = 0;
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? }
? ? ? ? }
? ? }
? ? if(flag==0)
? ? ? ? cout<<"no";
? ? else
? ? ? ? cout<<"yes";
}
?
總結
以上是生活随笔為你收集整理的判断字符串中的括号是否匹配——c和c++实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 技术人的自我学习
- 下一篇: 求int在二进制存储时1的个数(C++)