[Leetcode] 第299题 猜数字游戏

一、题目描述

请写出一个根据秘密数字和朋友的猜测数返回提示的函数,用 A 表示公牛,用 B 表示奶牛。

请注意秘密数字和朋友的猜测数都可能含有重复数字。

示例 1:

输入: secret = "1807", guess = "7810"

输出: "1A3B"

解释: 1 公牛和 3 奶牛。公牛是 8,奶牛是 0, 1 和 7

示例 2:

输入: secret = "1123", guess = "0111"

输出: "1A1B"

解释: 朋友猜测数中的第一个 1 是公牛,第二个或第三个 1 可被视为奶牛。

说明: 你可以假设秘密数字和朋友的猜测数都只包含数字,并且它们的长度永远相等

二、题目分析

1)cnt1和cnt2分别代表A和B的数目

2)统计出secret中字符出现的次数mp1<char,int>,然后统计在guess和secret中同时出现但是位置不正确字符的出现次数map2<char,int>

三、代码实现

 1 class Solution {
 2 public:
 3     string getHint(string secret, string guess) {
 4         unordered_map<char, int>mp1, mp2;
 5         int cnt1 = 0, cnt2 = 0;
 6         for (int i = 0; i < secret.size(); ++i) {
 7             ++mp1[secret[i]];
 8         }
 9         for (int i = 0; i < guess.size(); ++i) {
10             if (i < secret.size() && guess[i] == secret[i]) {
11                 --mp1[secret[i]];
12                 ++cnt1;
13             }
14             else if (mp1.find(guess[i]) != mp1.end()) {
15                 ++mp2[guess[i]];
16             }
17         }
18         for (auto it = mp2.begin(); it != mp2.end(); ++it) {
19             if (mp1[it->first] > 0)cnt2 += min(mp1[it->first], mp2[it->first]);
20         }
21         string res = itos(cnt1) + "A" + itos(cnt2) + "B";
22         cout << endl;
23         return res;
24     }
25 private:
26     string itos(int x) {
27         stringstream is;
28         is << x;
29         string res;
30         is >> res;
31         return res;
32     }
33 };

猜你喜欢

转载自www.cnblogs.com/zhizhiyu/p/10176167.html
今日推荐