问题描述:
编写程序,判断给定字符序列中(与),[与],{与}是否配对(个数相等)。
样例输入:
main(){int[] i;}}
样例输出:
NO
第一次错误还没有完全改正的部分
#include <iostream>
#include<vector>
#include<string>
using namespace std;
int Get(char x,char a[],int m,int n)
{
int i;
for(i=m;i<n;i++)
{
cout<<a[i]<<" ";
if(x=='('&&a[i]==')')
return 1;
else if(x =='['&&a[i]==']')
return 1;
else if(x=='{'&&a[i]=='}')
return 1;
}
return 0;
}
int main()
{
int n=0;
char a[100],b[100];
int i=0;
for(i=0;;i++)
{
scanf("%c",&a[i]);
//char x=getchar();
if(a[i]=='\n')
break;
}
n=i;
cout<<n;
for(int i=0;i<n;i++)
{
cout<<a[i];
}
int k=0;
//cout<<n;
//cout<<a.size();
i=0;
while(i<n)
{
//cout<<k;
//cout<<a[i]<<" ";
if(a[i]=='('||a[i]=='{'||a[i]=='[')//
{
k=Get(a[i],a,i,n);
//cout<<k;
if(k==0)
{
cout<<"NO";
return 0;
}
}
else if(a[i]==']'||a[i]==')'||a[i]=='}')
{
i++;
if(i>=n)
cout<<"NO";
return 0;
}
i++;
}
cout<<"YES";
return 0;
}
第二次引用的代码部分:
#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()
{
char str[1024];
gets(str);
int length = strlen(str);
int i = fun(str, 0, length-1);
if(i == 1){
printf("YES\n");
}else{
printf("NO\n");
}
return 0;
}
第三次修改代码(使用栈符合的部分)
#include<iostream>
#include<string>
#include<stack>
#include<stdio.h>
using namespace std;
int main()
{
int i;
char str[101],mark[101];
gets(str);
stack<char> s;
for(i=0;i<strlen(str);i++)
{
if(str[i]=='('||str[i]=='['||str[i]=='{')//对左括号进行入栈操作
{
s.push(i);
}
else if(str[i]==')'||str[i]==']'||str[i]=='}')//对右括号出站,注意出站前判断当前的栈是否是空的
{
if(s.empty())
{
cout<<"NO";
return 0;
}
else
{
s.pop();
}
}
}
while(!s.empty())//栈不空再一次判断当前栈中是否还有遗留的括号
{
cout<<"NO";
return 0;
}
cout<<"YES";
return 0;
}
参考链接:
https://blog.youkuaiyun.com/sjf0115/article/details/8675934
https://blog.youkuaiyun.com/u010431205/article/details/50554598