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.
Notice
You may assume both s and t have the same length.
Example
Given s = "egg", t = "add", return true.
Given s = "foo", t = "bar", return false.
Given s = "paper", t = "title", return true.
思路
用HashMap记录s与t每个字符对应关系
用HashSet记录t中的每个字符是否已经被匹配过
Conor Case: s与t如果长度不等,则直接返回false
遍历s和t,分别同时取s和t对应位置的字符,判断mapping是否包含s对应的字符, 如果不包含s对应的字符:
1)如果对应位置的t字符也不在set中(说明并未出现过),那么则向mapping中加入s和t对应字符,再向set中加入t对应字符
2)如果set中已经出现了对应位置的t字符。换句话,s没有出现过,但是t出现过了,比如s = 'aa', t = 'bc', 则说明t没有遵守pattern,返回false。-
如果包含s对应的字符(说明s对应字符已经出现):
1)如果mapping.get(s.charAt(i)) 不等于t.charAt(i), 则说明t没有遵守pattern,返回false。- 如果相等,说明遵守,什么也不做,继续。
相关题目
Word Pattern (http://www.jianshu.com/p/5fcef82f11ef)
Word Pattern II
public class Solution {
/*
* @param s: a string
* @param t: a string
* @return: true if the characters in s can be replaced to get t or false
*/
public boolean isIsomorphic(String s, String t) {
// write your code here
if (s == null || t == null ||s.length() != t.length()) {
return false;
}
HashMap<Character, Character> mapping = new HashMap<>();
Set<Character> set = new HashSet<Character>();
for (int i = 0; i < s.length(); i++) {
if (!mapping.containsKey(s.charAt(i))) {
if (set.contains(t.charAt(i))) {
return false;
}
mapping.put(s.charAt(i), t.charAt(i));
set.add(t.charAt(i));
} else {
if (mapping.get(s.charAt(i)) != t.charAt(i)) {
return false;
}
}
}
return true;
}
}