1039 到底买不买(附详细注释,逻辑分析 / 测试点2 4)

本文介绍了一种使用哈希表进行字符串匹配的算法,通过将字符映射为整型并存储在数组中计数,实现对目标字符串的有效比对。文章提供了两种实现方式,一种是通过自定义函数改变字符为整型,另一种直接利用ASCII码作为数组下标。最后总结了字符作为整型下标的便捷性和效率。
写在前面
  • 实现思路
    • 将字符串hash为整型,存储于整型数组中,并计数
    • 遍历目的字符串,字符对应计数减1
    • 下标区间覆盖,导致测试点2、4错误
  • 题目较简单,正常15分钟a题
测试用例
input:
ppRYYGrrYBR2258
YrR8RrY
output:
Yes 8

input:
ppRYYGrrYB225
YrR8RrY
output:
No 2
ac代码
  • 算法笔记(参考)
#include <iostream>
#include <cstring>
using namespace std;

const int maxn = 1010;
int hashTable[80] = {0}, miss=0;
int change(char c)
{
    if(c>='0' && c<='9') return c-'0';
    if(c>='a' && c<='z') return c-'a'+10;
    if(c>='A' && c<='Z') return c-'A'+36;
}
int main()
{
    char whole[maxn], target[maxn];
    scanf("%s", whole);
    scanf("%s", target);

    int len1 = strlen(whole);
    int len2 = strlen(target);
    for(int i=0; i<len1; i++)
    {
        int id = change(whole[i]);
        hashTable[id]++;
    }

    for(int i=0; i<len2; i++)
    {
        int id=change(target[i]);
        hashTable[id]--;
        if(hashTable[id]<0)
        {
            miss++;
        }
    }
    if(miss>0) printf("No %d", miss);
    else printf("Yes %d", len1-len2);

    return 0;
}
学习代码
#include <iostream>
using namespace std;
int book[256];
int main() {
    string a, b;
    cin >> a >> b;
    for (int i = 0; i < a.length(); i++)
        book[a[i]]++;
    int result = 0;
    for (int i = 0; i < b.length(); i++) {
        if (book[b[i]] > 0)
            book[b[i]]--;
        else
            result++;
    }
    if(result != 0)
        printf("No %d", result);
    else
        printf("Yes %d", a.length() - b.length());
    return 0;
}
知识点小结
// 字符作为整型下标,ascii自动转换
int book[256];
book[a[i]]++;

hashTable['a'] = 123;
cout << hashTable[97] << endl;
// 123
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

言析数智

创作不易,感谢客官的打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值