生活随笔
收集整理的這篇文章主要介紹了
判断字符串中的括号是否匹配-C语言
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
判斷字符串中的括號是否匹配-C語言
遞歸實現:
先檢搜一對匹配的括號,再對里面的內容進行匹配,匹配完后再繼續往下匹配……
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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;
}
把Hello World輸進去:
棧實現:
將字符逐個取出,若遇到左括號,則進棧;若遇到右括號,這時侯棧為空的話括號就不匹配,不為空,則出棧,并判斷左括號與右括號是否對;當字符串判斷完后,棧應為空,否則括號不匹配。棧是一種后進先出的數據結構,相關知識請自行百度
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STACKLENGTH 1024char stack[STACKLENGTH];
int top = STACKLENGTH;
int empty(){
if(top == STACKLENGTH)
return 1;
return 0;
}
void push(
char ch)
{top--;
stack[top] = ch;
}
char pop()
{
char ch =
stack[top];top++;
return ch;
}
int fun(
char *str)
{
while(*str !=
'\0'){
char chLeft =
'\0';
char chRight =
'\0';
char ch = *str;
switch(ch){
case '(':
case '[':
case '{':push(ch);
break;
case ')':chLeft =
'(';chRight = ch;
break;
case ']':chLeft =
'[';chRight = ch;
break;
case '}':chLeft =
'{';chRight = ch;
break;
default:
break;}
if(chRight == ch) {
if(empty()){
return 0;}
else{
char t = pop();
if(t != chLeft){
return 0;}}}str++;}
if(empty()){
return 1;}
return 0;
}
int main(
void)
{
char array[
1024];gets(
array);
int i = fun(
array);
if(i ==
1){
printf(
"括號匹配!\n");}
else{
printf(
"括號不匹配!\n");}
return 0;
}
試一試:
編譯環境:Dev-C++5.11
總結
以上是生活随笔為你收集整理的判断字符串中的括号是否匹配-C语言的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。