题目:
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.
思路:
- 题意:给定两个同样长度的字符串,判断这两个字符串是不是同形,所谓同形就是,两个字符串相等的地方一样,如上面举例的字符串。
- 可以利用判断字符串是不是有重复字符的思路,把字符串转化为数组,存进hashMap,判断是否有重复值,有了判断相应的坐标是不是相同,不相同,或者不同时出现重复,均为不满足条件。出现重复,去掉重复,添加新元素,不重复,只是添加新元素。
-
代码:
public class Solution {
public boolean isIsomorphic(String s, String t) {
if(s == null){
return true;
}
char[] a = s.toCharArray();
char[] b = t.toCharArray();
int n = a.length;
Map<Character,Integer> aa = new HashMap<Character,Integer>();
Map<Character,Integer> bb = new HashMap<Character,Integer>();
for(int i = 0;i < n;i++){
if(aa.containsKey(a[i])){
if(!bb.containsKey(b[i])){
return false;
}else{
int c = aa.get(a[i]);
int d = bb.get(b[i]);
if(c != d){
return false;
}else{
aa.remove(a[i]);
bb.remove(b[i]);
aa.put(a[i],i);
bb.put(b[i],i);
}
}
}else{
if(bb.containsKey(b[i])){
return false;
}else{
aa.put(a[i],i);
bb.put(b[i],i);
}
}
}
return true;
}
}