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: true
Example 2:
Input: s ="foo",
t ="bar"
Output: false
Example 3:
Input: s ="paper",
t ="title"
Output: true
Note:
You may assume both s and t have the same length.
我的解法,用了hashmap
HashMap<Character, Character> chara = new HashMap<Character, Character>();
for (int i = 0; i < s.length(); i++) {
char source = s.charAt(i);
if (chara.containsKey(source))
if (chara.get(source) == t.charAt(i))
continue;
else
return false;
else if (chara.containsValue(t.charAt(i)))
return false;
else
chara.put(s.charAt(i), t.charAt(i));
}
return true;
shpolsky的解法,其实就是看对应的字符上次是否同时出现~
public class Solution {
public boolean isIsomorphic(String s1, String s2) {
int[] m = new int[512];
for (int i = 0; i < s1.length(); i++) {
if (m[s1.charAt(i)] != m[s2.charAt(i)+256]) return false;
m[s1.charAt(i)] = m[s2.charAt(i)+256] = i+1;
}
return true;
}
}