题目描述:
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.
解题思路:
用一个map来记录字符之间的映射关系
用set来记录出现过的字符
S[i] ,t[i]
如果s[i]没有出现过:
- 如果t[i]也没出现过:将其加入到map中
- 如果t[i]出现过:说明是多对一,return false
如果s[i]出现过:说明(s[i]==s[k]): - t[i] ==t[k] return true
- t[i] !=t[k] return false
代码:
class Solution {
public boolean isIsomorphic(String s, String t) {
if(s==null && t==null)
return true;
else if(s==null || t==null)
return false;
else if(s.length()!=t.length())
return false;
Map<Character, Character> map = new HashMap<Character, Character>();
Set<Character> set = new HashSet<>();
for(int i=0;i<s.length();i++){
char s1 = s.charAt(i);
char t1 = t.charAt(i);
if(!map.containsKey(s1)){
if(set.contains(t1))
return false;
else{
map.put(s1, t1);
set.add(t1);
}
}else{
if(map.get(s1)!=t1)
return false;
}
}
return true;
}
}