C++ two hash table very clear code


  • 0
    Y

    class Solution {

    public:

    bool isIsomorphic(string s, string t) {
        map<char, int> myMap1;
        map<char, int> myMap2;
        
        for (int i = 0; i < s.length(); i++) {
            myMap1[s[i]] += i + 1;
            myMap2[t[i]] += i + 1;
        }
        
        for (int i = 0; i < s.length(); i++) {
            if (myMap1[s[i]] != myMap2[t[i]]) return false;
        }
        
        return true;
    }
    

    };


  • 1
    W

    Wrong code!
    try the case "aaca" "bbdd"


  • 0
    Y

    Can u explain why this is wrong? Did you try that?


  • 0
    W

    Please try the case
    "aaca" "bbdd"
    your answer is true, the expected answer is false.

    when i = 3, the state of the two hash tables are
    h1['a'] = 3 h2['b'] = 3 h1['c'] = 3 h2['d'] = 3
    so it will treat any a->b, a->d, b->c, b->d mapping as true.


  • 0
    Y

    I tried it using the custom testcase functionality in leetcode but it gives false for the case "aaca" "bbdd".

    I dont think h1['a'] = 3 h2['b'] = 3 h1['c'] = 3 h2['d'] = 3 correct?
    When i = 3, h1['a'] = 7.


  • 0
    W

    Are u sure you post the correct code above?
    cause i copy your code and ran it using the custom testcase functionality in leetcode.
    It gives 'true'. When i said "i = 3", i mean before executing the loop "i = 3"


  • 0
    Y

    OK, I have made a small change and it should work now.


  • 0
    W

    yes, it works


Log in to reply
 

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