字符串匹配

来源:互联网 发布:保罗10年季后赛数据 编辑:程序博客网 时间:2024/06/16 20:39

面试题:给一串很长的字符串,要求找到符合要求的字符串,例如目的串:”123”

“1****3***2”,”12*****3”这些都要找出来

思路一:

利用两层循环,逐个查找目的串中的字符,比如先查找字符’1’是否在长字符串中,再查找’2’是否在长字符串中,直到目的串遇到’\0’

代码是:

# include <stdio.h># include <stdlib.h># include <string.h>int main(){int ismatch(char *s1,char *s2);char a[10]="123";char b[20]="31**123*sdj*sd728";printf("%d\n",ismatch(a,b));    system("pause");    return 0;}int ismatch(char *s1,char *s2) //目的串在s1中,长字符串在s2中{int len1=strlen(s1);int len2=strlen(s2);int *count=(int *)malloc(sizeof(int));int i=0,j=0;for(i=0;i<len1;i++){count[i]=0;for(j=0;j<len2;j++){if(s1[i]==s2[j])      //目的串的字符在长字符串中出现            count[i]=1;    }}for(i=0;i<len1;i++){if(count[i]==0)return 0;}return 1;}

思路二:

先建立一个字符数组c[256],初始化为0,遍历目的串,如果目的串出现了某个字符a,则将c[a]=1,然后遍历长字符串,如果长字符串出现了字符a,则将c[a]=0.

如果目的串的字符均出现在长串中,最后c[256]应该全是0。

代码是:

# include <stdio.h># include <stdlib.h># include <string.h>int main(){int ismatch(char *s1,char *s2);char a[10]="123";char b[20]="31**123*sdj*sd728";printf("%d\n",ismatch(a,b));    system("pause");    return 0;}int ismatch(char *s1,char *s2)  //目的串在s1,长字符串在s2中{char count[256];int i=0;int len=strlen(s1);for(i=0;i<256;i++)              //初始化count[i]=0;for(i=0;i<len;i++)count[s1[i]]=1;len=strlen(s2);for(i=0;i<len;i++)count[s2[i]]=0;for(i=0;i<256;i++){if(count[i]==1)return 0;}return 1;}



0 0
原创粉丝点击