Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to gett.
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.
public class Solution {
public boolean isIsomorphic(String s, String t) {
HashMap<Character,Integer>maps=new HashMap<Character,Integer>();
HashMap<Character,Integer>mapt=new HashMap<Character,Integer>();
for(Integer i=0;i<s.length();i++){
if(maps.put(s.charAt(i),i)!=mapt.put(t.charAt(i),i)) return false; //put返回的key锁对应的上一个值
}
return true;
}
}
public class Solution {
public boolean isIsomorphic(String s, String t) {
HashMap<Character,Character>maps=new HashMap<Character,Character>();
HashSet<Character>set=new HashSet<Character>();//set是一元的并且不允许有重复元素
for(Integer i=0;i<s.length();i++){
if(maps.containsKey(s.charAt(i))){
if (maps.get(s.charAt(i))!=t.charAt(i)) return false;
}
else{
if(set.contains(t.charAt(i))) return false;//注意这儿要先行判断
else{
maps.put(s.charAt(i),t.charAt(i));//key,value为字符串s和t里边对应位置的字母
set.add(t.charAt(i));//set维护t里边的字母
}
}
}
return true;
}
}
/*public class Solution {
public boolean isIsomorphic(String s, String t) {
HashMap<Character,Integer>maps=new HashMap<Character,Integer>();
HashMap<Character,Integer>mapt=new HashMap<Character,Integer>();
for(Integer i=0;i<s.length();i++){
if(maps.containsKey(s.charAt(i))) maps.put(s.charAt(i),maps.get(s.charAt(i))+1);
else maps.put(s.charAt(i),1);
}
for(Integer i=0;i<t.length();i++){
if(mapt.containsKey(t.charAt(i))) mapt.put(t.charAt(i),mapt.get(t.charAt(i))+1);
else mapt.put(t.charAt(i),1);
}
for(Integer i=0;i<s.length();i++){
if(maps.get(s.charAt(i))!= mapt.get(t.charAt(i))) return false; //有错,把hashmap当做有序存放的了,记得他只跟key有关
}
return true;
}
}*/