探究一道字符串模式匹配问题

一 问题


二 解题思路


正如上图所示,采用一个辅助数组arr来记录字符串str中具有单词的位置,例如单词WORLD确实出现在字符串str中,那么与之对应的arr区域都是1,那么扫描完arr,就可以输出 所有的单词。

三 运行结果


四 代码

/*
 * 2014 weipinghui  xiaoyuan recruitment
 * a method of string pattern match
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define SIZE 1024
const char *dictionary = "hello,world";   // to define a pattern string
void StringToWord(const char *str) {
		int *arr;                  // to locate the target
		char tmp[SIZE];
		int i, j, k;
		int cnt;                  // the counter of matched string
		int m;
		int start;
		int n = strlen(str);
		j = 0;
		arr = (int *)malloc(sizeof(int) * n);  
        memset(arr, 0 , sizeof(arr));
		for(i = 0;dictionary[i];i++) {
				if(dictionary[i] != ',') {
						tmp[j++] = dictionary[i];
				}
				/*
				 * to get a string
				*/
				if(dictionary[i] == ',' || !dictionary[i + 1])  {
						tmp[j] = '\0';
						start = 0;
						/*
						 * to match
						*/
						while(start < n) {
								const char *p = strstr(str + start, tmp);
								if(!p) break;   // there is no match
								cnt = 0;
								m = strlen(tmp);
								k = p - str;    // wherer to start
								while(cnt < m) {
										arr[k++] = 1;
										cnt++;
								}
								start = p - str + strlen(tmp);
						}
						j = 0;
				}
		}
		for(i = 0;i < n;i++) {
				if(arr[i]) putchar(str[i]);
		}
		putchar('\n');
		free(arr);
}
int main() {
		char str[SIZE];
		gets(str);
		StringToWord(str);

		return 0;
}

五 编程体会

    采用辅助空间是个小小技巧,但时间复杂数有点高哦。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值