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.
题意:
字符串A与字符串B进行比较,保证A和B的长度相等。
bull:相应下标下字符相等,bull++
cow:字符串B和字符串A中字符相同但下标不同的个数。
用数组和unordered_map<char,int> table记录字符c出现的次数
方法一:扫描两次
第一次:计算bull,扫描A,B
第二次:计算cow,扫描B
方法二:扫描一次
在扫描过程中,假定第i个下标时,A的字符为ca,B的字符为cb,在扫描过程中,table[ca]++,table[cb]--;
情况1:table[ca]==table[cb] 则bull++;
情况2:
a)table[ca]<0,则说明当前字符ca在扫描[0——i-1]的下标时,在字符串B中出现过(table[cb]--,因对字符串B中的cb执行的是减一操作),这种情况处理的是,字符c在串A的出现时间比串B出现的晚。
b)table[cb]>0,则说明当前字符cb在扫描[0——i-1]的下标时,在字符串A中出现过(table[ca]++,因对字符串A中的ca执行加一操作),这种情况处理的是,字符c在串A的出现时间比串B出现的早。
对a,b两种情况均要判断。在判断完 a,b后,要执行相应的--和++操作,
stringgetHint(stringsecret,stringguess){intlen_s=secret.length(),len_g=guess.length();if(len_s==0)return"";intnuma=0,numb=0;//unordered_map<char,int>table;inttable[10]={0};/*for(inti=0;i<len_s;++i){if(secret[i]==guess[i]){numa++;}table[secret[i]]++;}for(inti=0;i<len_s;++i){if(table.find(guess[i])!=table.end()&&table[guess[i]]>0){--table[guess[i]];numb++;}}*/for(inti=0;i<len_s;++i){if(secret[i]==guess[i]){numa++;}else{if(table[secret[i]-'0']++<0)numb++;if(table[guess[i]-'0']-->0)numb++;//table[secret[i]]++;//table[guess[i]]--;}}//cout<<numa<<numb-numa;//stringres=to_string(numa)+"A"+to_string(numb)+"B";returnto_string(numa)+"A"+to_string(numb)+"B";}
returnto_string(numa)+"A"+to_string(numb)+"B"减少了一次字符串构建和拷贝过程。可以利用RVO,用数组比unordered_map<>更减少时间开销,从12ms减小到4ms,
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。