Description
Given two strings S and T, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
For example,
- Given "egg", "Add", return true.
- Given "foo", "bar", return false.
- Given "Paper", "title", return true.
- Given "AB", "AA", return false.? A-> A and B->
Note:You may assume both S and T have the same length.
This is a simple question. You do not have to consider the case where two strings have different lengths. Traverse the string and use map to obtain the ing between the two strings. If the new character pair is different from the one saved in map, false is returned.
Note that the use of a map may fail to judge the situation of "AB" and "AA", because the keys from A-> A and B-> A are different, it cannot be found in the map, but in turn a-> A and A-> B are obviously incorrect. Therefore, we can use the two strings as the map key, respectively, make two judgments to avoid errors.
Another approach is to use only one string as the map key, but use a set to save the value of each key. If the number of elements in the set is smaller than the number of map elements after processing, two different keys are mapped to the same value, and false is returned.
Code
class Solution {public: bool isIsomorphic(string s, string t) { if(s.size() != t.size()) return false; unordered_map<char, char> stringMap; for(size_t i = 0; i != s.size(); ++i) { char sc = s[i]; char tc = t[i]; if (stringMap.find(sc) == stringMap.end()) { stringMap[sc] = tc; } else { if (stringMap[sc] != tc) return false; } } unordered_set<char> stringSet; unordered_map<char, char>::iterator it = stringMap.begin(); for(; it != stringMap.end(); ++it) { if (stringSet.find(it->second) != stringSet.end()) return false; else stringSet.insert(it->second); } return true; }};
Leetcode (35) isomorphic strings