Problem:
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.
Example 1:
Input: s = "egg", t = "add" Output: trueExample 2:
Input: s = "foo", t = "bar" Output: falseExample 3:
Input: s = "paper", t = "title" Output: trueNote:
You may assume both s and t have the same length.
Analysis:
本题的问题是对任意的字符串需要保证其映射的唯一性,也就是意义映射,如不满足这个规则就返回false。这里我们维持两个Map来保证其实唯一的映射关系。代码如下:
Code:
class Solution {
public boolean isIsomorphic(String s, String t) {
if(s.length() != t.length())
return false;
Map<Character, Character> temp1 = new HashMap<Character, Character>();
Map<Character, Character> temp2 = new HashMap<Character, Character>();
for(int i = 0; i < t.length(); i++) {
if(temp1.containsKey(t.charAt(i))) {
if(s.charAt(i) != temp1.get(t.charAt(i))) {
return false;
} else {
continue;
}
} else {
temp1.put(t.charAt(i), s.charAt(i));
}
if(temp2.containsKey(s.charAt(i))) {
if(t.charAt(i) != temp2.get(s.charAt(i))) {
return false;
} else {
continue;
}
} else {
temp2.put(s.charAt(i), t.charAt(i));
}
}
return true;
}
}