Leetcode[205] Isomorphic Strings
17 Nov 2015###Task1 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.
Note: You may assume both s and t have the same length.
###Python
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
map = {}
for i in range(len(s)):
if s[i] in map and map[s[i]] != t[i]:
return False
elif s[i] not in map and t[i] in map.values():
return False
elif s[i] not in map:
map[s[i]] = t[i]
return True
###Java
public class Solution {
public boolean isIsomorphic(String s, String t) {
if (s == null || t == null) {
return false;
}
HashMap<Character, Character> map = new HashMap<Character, Character>();
for (int i = 0; i < s.length(); i++) {
if (!map.containsKey(s.charAt(i))) {
if (!map.containsValue(t.charAt(i))) {
map.put(s.charAt(i), t.charAt(i));
} else {
return false;
}
} else {
char pair = map.get(s.charAt(i));
if (pair != t.charAt(i)) {
return false;
}
}
}
return true;
}
}
###Points
- one char map to one and only one char