【字符串处理】构造长度为4的字符串,不足4位的用0补够4位

关键函数 insert(pos,length, ch)

string num = to_string(i);
num.insert(0, 4 - num.size(), '0');

image

例题:猜数字

image

样例1
输入

6
4815 1A1B
5716 0A1B
7842 0A1B
4901 0A0B
8585 3A0B
8555 2A1B

输出

3585

C++代码

#include <cstring>
#include <iostream>
#include <unordered_map>

using namespace std;

int n, cnt1[10], cnt2[10];
unordered_map<string, string> h;

string cal(string &ans, string s)
{
    memset(cnt1, 0, sizeof cnt1);
    memset(cnt2, 0, sizeof cnt2);
    for (char &x : ans) cnt1[x - '0']++;
    for (char &x : s) cnt2[x - '0']++;

    int a = 0, b = 0;
    for (int i = 0; i < 4; i++)
    {
        if (ans[i] == s[i]) a++;
        else if (ans.find(s[i]) != string::npos)
        {
            b++;
            if (cnt1[s[i] - '0'] < cnt2[s[i] - '0']) b--; //关键,处理同一字符出现多次的情况
        }
    }
    return to_string(a) + "A" + to_string(b) + "B";
}

string solve()
{
    string res = "NA";
    for (int i = 0; i <= 9999; i++)
    {
        string num = to_string(i);
        num.insert(0, 4 - num.size(), '0');
        bool flag = false;
        for (auto &[k, v] : h)
        {
            string t = cal(num, k);
            if (t != v)
            {
                flag = true;
                break;
            }
        }
        if (flag) continue;
        else
        {
            if (res != "NA") return "NA";
            res = num;
        }
    }
    return res;
}

int main()
{
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        string num, s;
        cin >> num >> s;
        h[num] = s;
    }
    cout << solve();
    return 0;
}
posted @   Tshaxz  阅读(1)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· Trae初体验
Language: HTML
点击右上角即可分享
微信分享提示