- 要求实现函数:
void analysis(char *str,int *num)
【输入】 char *str,待分析字符串
【输出】 int num,匹配的组合个数
【返回】 无
注:输入字符串中关键字以空格隔开,"if"、"("、")"、"case"等均表示关键字,从左向右,找到匹配的组合即可,组合一定是相互分离,不会嵌套,不会有交叉情况出现。
1) 输入:str = if then,
输出:num = 1
2) 输入:str = switch case aaa ,
输出:num = 0
3) 输入:str = if ( aaa ) then dobbb while switch cas ,
输出:num = 2
问题分析:
由于输入的关键字不会嵌套,所以可以一次匹配每个单词。 如果一个单词匹配了if 只要寻找 then 就行了,不用考虑中间的括号。对于switch ( ) case default end 只要考虑switch case end就行。
下面提供一种实现:
#include <errno.h>
#include<list>
#include<algorithm>
#include<cstdio>
#include<vector>
#include <iostream>
#include<string>
#include<stack>
#define INT_MAX (1<<30)
using namespace std;
int proc(vector<string>& s,vector<string>& vec){
int j=0;
int count=0;
for(size_t i=0;i<s.size();++i){
if(s[i]==vec[j]){
j++;
}
if(j==vec.size()) {
j=0;
count++;
}
}
return count;
}
void analysis(char *str,int *num){
vector<string> s;
char* p=str;
string tmp="";
while(*p){
if(*p!=' ') tmp+=*p;
else{ s.push_back(tmp);tmp="";}
p++;
}
if(tmp!="") s.push_back(tmp);
string strs[]={"if","then"};
vector<string> vec(strs,strs+sizeof(strs)/sizeof(string));
int count=0;
count+=proc(s,vec);
vec.clear();
vec.push_back("switch");vec.push_back("case");vec.push_back("end");
count+=proc(s,vec);
vec.clear();
vec.push_back("do");vec.push_back("while");
count+=proc(s,vec);
*num=count;
}
int main(){
char src[]="if ( aaa ) then do bbb while switch cas";
int num;
analysis(src,&num);
cout<<num<<endl;
return 0;
}