2011华为编程大赛B卷第三道题

来源:互联网 发布:网络盗号报警 编辑:程序博客网 时间:2024/04/28 23:17
3 、字符串匹配( 50 分) 
  问题描述 
判断包含通配符的匹配字符串是否完全匹配输入的字符串,匹配字符串中包含的通配符仅有‘ * ’和‘?’,且通配符不会连续出现 。(要求完全匹配,而不是包含) 
其中,通配符‘ * ’:代替 0 个或多个字符,通配符‘ ? ’:代替一个字符 
  要求实现函数 
int GetMatchSta (const char *ArrStr, const char *KeyStr) 
【输入】 ArrStr :    给定的字符串 
KeyStr :       包含通配符的匹配字符串 
【输出】 无 
【返回】是否匹配,匹配返回1 ,不匹配返回0 
  示例 
输入: ” abcdefg”, “a*'” 
返回: 1 
输入: “tommababcabc” , t?m*ab*abc 

返回: 1 


以下代码可满足题目给出的试例要求,但当输入分别为"abcbde" ,"*bde"时,本应返回1,程序返回0。有待改进

#include "stdafx.h"#include "iostream"using namespace std;int GetMatchSta (const char *ArrStr, const char *KeyStr) {while(*KeyStr != '\0' && *ArrStr != '\0'){if (*KeyStr == '?'){KeyStr++;ArrStr++;}else if (*KeyStr == '*'){KeyStr++;while (*ArrStr != '\0' && *KeyStr != *ArrStr)// 有问题,abcbde   *bde{ArrStr++;}}else if (*KeyStr == *ArrStr){KeyStr++;ArrStr++;}else if (*KeyStr != *ArrStr){break;}}if (*KeyStr == '\0' && *ArrStr == '\0'){return 1;}else{return 0;}}int _tmain(int argc, _TCHAR* argv[]){char ArrStr[] = "abcbde";char KeyStr[] = "*bde";cout << "给定字符串为:" << ArrStr << endl;cout << "用于匹配字符串为:" << KeyStr << endl;cout << "匹配情况为" << GetMatchSta(ArrStr, KeyStr) << endl;system("pause");return 0;}

写了下没写出来,然后就上网找了下代码。。。尴尬尴尬尴尬如下。。。你们别拉我,让我死了吧。。。。这就是差距。。。

#include "stdafx.h"#include "iostream"using namespace std;int GetMatchStr (const char *ArrStr, const char *KeyStr) {switch (*KeyStr){case '\0':return (*ArrStr=='\0')? 1:0;case '?':return (*ArrStr=='\0')? 0:GetMatchStr(ArrStr+1,KeyStr+1);case '*':return (*ArrStr=='\0')? GetMatchStr(ArrStr,KeyStr+1):GetMatchStr(ArrStr+1,KeyStr)|GetMatchStr(ArrStr,KeyStr+1);default:return (*ArrStr!=*KeyStr)? 0:GetMatchStr(ArrStr+1,KeyStr+1);}}int _tmain(int argc, _TCHAR* argv[]){char ArrStr[] = "abcbde";char KeyStr[] = "*bde";cout << "给定字符串为:" << ArrStr << endl;cout << "用于匹配字符串为:" << KeyStr << endl;cout << "匹配情况为" << GetMatchStr(ArrStr, KeyStr) << endl;system("pause");return 0;}

如此简洁。。。

0 0