299.[leetcode]Bulls and Cows
2016-06-08 22:05
309 查看
题意就不赘述
我的做法
class Solution { public: string getHint(string secret, string guess) { vector<char> _guess; multiset<char> _secret; multiset<char>::iterator it; ostringstream b,c; int length = secret.size(); int bulls = 0; int cows = 0; // count bulls for(int i=0; i<length;i++){ if(secret[i]!=guess[i]) { _secret.insert(secret[i]); _guess.push_back(guess[i]); } else { bulls++; } } // count cows for(int i=0; i<_guess.size();i++){ it = _secret.find(_guess[i]); if(it != _secret.end()) { cows++; _secret.erase(it); } } // 输出部分 sstream string result,bulls_num,cows_num; b << bulls; bulls_num = b.str(); c << cows; cows_num = c.str(); result = bulls_num + "A" + cows_num + "B"; return result; } };
大神做法
string getHint(string secret, string guess) { vector<int>tb_guess(10),tb_secret(10); int A=0,B=0; for (int i=0;i<secret.size();++i){ if (secret[i]==guess[i]) A++; else { tb_guess[guess[i]-'0']++; tb_secret[secret[i]-'0']++; } } for (int i=0;i<10;++i){ B=B+ min(tb_guess[i],tb_secret[i]); } return to_string(A)+'A'+to_string(B)+'B'; }
关键在这个,题中有一个重要的信息是:只可能是数字, 也就是只可能是 0-9
这时只要用两个10大小的 vector 记录下,不同的数字出现的次数,去两者最小(也就是重叠的部分),就好了
ps:使用std 的 to_string 也比 sstream好的多
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解