[Rainbow] 3-pass but really easy to understand C++ solution


  • 0
    class Solution {
    public:
        string getHint(string secret, string guess) {
            vector<int> dict(128, 0);
            int A=0, B=0;
            for(auto c:secret)  dict[c]++;
            for(auto c:guess){
                if(dict[c]){
                    dict[c]--;
                    B++;
                }
            }
            for(int i=0; i<secret.size(); i++){
                if(secret[i]==guess[i]) A++;
            }
            
            return to_string(A).append("A").append(to_string(B-A)).append("B");
        }
    };
    

    Here is also a 2 pass solution

    class Solution {
    public:
        string getHint(string secret, string guess) {
            int c1=0, c2=0;
            int a=0, b=0;
            vector<int> v1(10, 0), v2(10, 0);
            if(secret.size()!=guess.size() || secret.size()==0)  return "0A0B";
            for(int i=0; i<secret.size(); i++){
                char ch1=secret[i], ch2=guess[i];
                if(ch1==ch2) a++;
                else { v1[ch1-'0']++;  v2[ch2-'0']++; }
            }
            /** idea : min-occurence of all the number in the secret **/
            for(int i=0; i<v1.size(); i++)  c2+=min(v1[i], v2[i]);
            return to_string(a) + 'A' + to_string(b) + 'B';
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.