C++ two hash table very clear code

• 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;
}
``````

};

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

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

"aaca" "bbdd"

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.

• 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.

• 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"

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

• yes, it works

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