299. 猜数字游戏
1 // 统计个数,相同位置相同数字的个数--->A的个数 2 // 不同位置相同数字的个数--->B的个数 3 class Solution 4 { 5 public: 6 string getHint(string secret, string guess) 7 { 8 int n = secret.size(); 9 int A_count = 0; //相同位置相同数字的个数 10 int all_count = 0; //相同数字的个数 11 for(int i = 0;i < n;i ++) 12 { 13 if(secret[i] == guess[i]) A_count ++; 14 } 15 16 unordered_map<char,int> hash1,hash2; 17 for(auto a : secret) hash1[a] ++; 18 for(auto a : guess) hash2[a] ++; 19 for(auto b : hash1) 20 { 21 if(hash2.count(b.first)) all_count += min(b.second,hash2[b.first]); 22 } 23 24 return to_string(A_count) + "A" + to_string(all_count - A_count) + "B"; 25 } 26 };
Mamba never out

浙公网安备 33010602011771号