C++ 4ms O(n) time, O(1) space


  • 0
    Z
    #include <iostream>
    #include <string>
    #include <unordered_map>
    using namespace std;
    
    class Solution {
    string solution1(string s, string g);
    public:
    string getHint(string secret, string guess) {
        return solution1(secret, guess);
    }
    };
    
    string Solution::solution1(string s, string g){
    int ms[128] = {}, mg[128] = {};
    int A(0), B(0);
    for(int i = 0; i < s.length(); i++){
        int ts(s[i]), tg(g[i]);
        if(ts == tg) A++;
        else{
            ms[tg] ? ms[tg]--, B++ : mg[tg]++;
            mg[ts] ? mg[ts]--, B++ : ms[ts]++;
        }
    }
    return to_string(A) + 'A' + to_string(B) + 'B';
    }

  • 0
    T

    Hmm, interesting balancing the two arrays.


Log in to reply
 

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