华为机试-字符串匹配(HJ81)-纯C

字符串匹配

http://www.nowcoder.com/questionTerminal/22fdeb9610ef426f9505e3ab60164c93

纯C

题目标题:判断短字符串中的所有字符是否在长字符串中全部出现

是判断短字符串中所有字符有否有在长字符串中全部出现,并不是判断短字符串是否是长字符串的字串,那么就很简单了(判断子串也很简单)。

毫无疑问就是哈希表了。

时间复杂度:O(n)
空间复杂度:O(1)

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int IsAllCharExist(char* pShortString,char* pLongString)
{
    int len_short = strlen(pShortString);
    int len_long = strlen(pLongString);
    int hash_table[128] = {0};
    int count = 0;
    for(int i=0; i<len_long; i++)
    {
        hash_table[pLongString[i]]=1;
    }
    for(int i=0; i<len_short; i++)
    {
        if(hash_table[pShortString[i]])
            count++;
    }
    if(count == len_short)
        return 1;
    else
        return 0;
}

int main()
{
    char str_short[50]={'\0'}, str_long[200]={'\0'};
    while(gets(str_short))
    {
        gets(str_long);
        int flag = IsAllCharExist(str_short, str_long);
        if(flag)
            printf("true\n");
        else
            printf("false\n");
    }
    return 0;
}
全部评论
为什么是把长字符串里面的值变成1再与短字符串对照,但是反过来就不行了呢
点赞 回复 分享
发布于 2022-08-12 16:28

相关推荐

评论
6
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务