日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

判断字符串中的括号是否匹配——c和c++实现

發布時間:2024/4/18 c/c++ 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 判断字符串中的括号是否匹配——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++实现的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。