• + 0 comments

    Genius solution. Thanks for sharing!

    The solution is: for each character combination of 2, consider if it's possible for them to be the only remaining characters.
    
    ex: aacbb
    There are 3 scenarios to consider:
    1. only 'a' and 'b' remaining. It's "aabb", and doesn't satisfy the criteria.
    2. only 'a' and 'c' remaining. It's "aac", also not okay.
    3. only 'b' and 'c' remaining. It's "cbb", also not okay.
    
    So, in the following 3x3 matrix:
      a b c
    a 
    b 
    c 
    (a,b) or (b,a) represents the scenario "only 'a' and 'b' remaining". 
    When we read the first 'a' in "aacbb", the matrix becomes:
      a b c
    a a a a
    b a
    c a
    
    so for (a,b), or "if you want only 'a' and 'b' in the remaining string", the 'a' will be the last character. Then we add the second 'a' in "aacbb". Notice that for (a,b), 'a' is already the last character and adding it will create an "aa" duplicate. Thus (a,b) is impossible.
    

    Hope this explanation makes it clear. If not, writing down on a paper helps. My code:

    int alternate(string s) {
        array<array<char,26>,26> tbl_dup;
        array<array<int,26>,26> tbl_cnt;
    
        // Initilization
        for (int i(0); i < 26; ++i) {
            for (int j(0); j < 26; ++j) {
                tbl_dup[i][j] = '\0';
                tbl_cnt[i][j] = 0;
            }
        }
    
        // Go over s
        for(int i(0);i<s.size();++i){
            char ch = s[i];
            for(int j(0);j<26;++j){
                if (tbl_dup[ch-'a'][j] == ch){
                    // The combination of the char ch and the char 'a'+j is impossible.
                    tbl_cnt[ch-'a'][j] = -1;
                    tbl_cnt[j][ch-'a'] = -1;
                }
                else{
                    bool no_longer_count = (tbl_cnt[ch-'a'][j] == -1);
                    tbl_dup[ch-'a'][j] = ch;
                    if(!no_longer_count)
                        ++tbl_cnt[ch-'a'][j];
    
                    if((ch-'a')!=j){
                        tbl_dup[j][ch-'a'] = ch;
                        if(!no_longer_count)
                            ++tbl_cnt[j][ch-'a'];
                    }
                }
            }
        }
    
        int max = -1;
        for(int i(0);i<26;++i){
            for(int j(i);j<26;++j){
                if(tbl_cnt[i][j] > max)max = tbl_cnt[i][j];
            }
        }
        return (max<=1)?0:max;
    }