2012 华为编程大赛 语法分析

  • 要求实现函数:

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;
 
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值