leetCode 299. Bulls and Cows 哈希
299. Bulls and Cows
You are playing the followingBulls and Cowsgame with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number.
For example:
Secretnumber:"1807"Friend'sguess:"7810"
Hint:1
bull and3
cows. (The bull is8
, the cows are0
,1
and7
.)
Write a function to return a hint according to the secret number and friend's guess, useA
to indicate the bulls andB
to indicate the cows. In the above example, your function should return"1A3B"
.
Please note that both secret number and friend's guess may contain duplicate digits, for example:
Secretnumber:"1123"Friend'sguess:"0111"
In this case, the 1st1
in friend's guess is a bull, the 2nd or 3rd1
is a cow, and your function should return"1A1B"
.
You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.
思路:
1.遍历两个字符串A,B,如果某一位置的字符相等,那么bull++,否则将A中的字符放入一个vector中,B中的字符放入一个mutiset中。
2.遍历vector A,如果在B的mutiset中找到相等的元素,cow++,将这个元素从mutiset中删除。
3.组织字符串。
代码如下:
classSolution{public:stringgetHint(stringsecret,stringguess){vector<char>secretVector;multiset<char>guessMulSet;inti;intbulls=0;intcows=0;for(i=0;i<secret.size();i++){if(secret[i]==guess[i])bulls++;else{secretVector.push_back(secret[i]);guessMulSet.insert(guess[i]);}}intvecLen=secretVector.size();for(i=0;i<vecLen;i++){if(guessMulSet.find(secretVector[i])!=guessMulSet.end()){cows++;guessMulSet.erase(guessMulSet.find(secretVector[i]));}}stringresult="";stringstreamss;stringstreamss1;ss<<bulls;stringbullStr=ss.str();ss1<<cows;stringcowStr=ss1.str();result+=bullStr;result+="A";result+=cowStr;result+="B";returnresult;}};
总结:这里使用到了mutiset这一容器,该容器允许出现重复的值。
2016-08-13 13:21:15
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。