Created
February 23, 2016 06:02
-
-
Save pradeep1288/e45b2843d3ede158a504 to your computer and use it in GitHub Desktop.
Isomorphic Strings.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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. | |
*/ | |
class Solution { | |
public: | |
bool isIsomorphic(string s, string t) { | |
if (s.size() != t.size()) { | |
return false; | |
} | |
map<char,char> strMap; | |
map<char,int> alreadyMapped; | |
for (int i=0; i<t.size(); i++) { | |
if(strMap[s[i]]) { | |
if (strMap[s[i]] == t[i]) { | |
continue; | |
} else { | |
return false; | |
} | |
} else { | |
if (alreadyMapped[t[i]]) { | |
return false; | |
} | |
strMap[s[i]] = t[i]; | |
alreadyMapped[t[i]] = 1; | |
} | |
} | |
return true; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment