Subject
https://leetcode.com/problems/isomorphic-strings/
Explain
判断两个字符串是否是”同构“字符串。
Solution
通过一个 map 来存储两个字符串的字符,key-value。一次读取两个字符串的字符,然后进行判断即可。
/**
* HashMap
* 25ms
*
* @param s
* @param t
* @return
*/
public boolean isIsomorphic(String s, String t) {
if (s == null && t == null) {
return true;
}
if (s == null && t != null) {
return false;
}
if (s != null && t == null) {
return false;
}
if (s.length() != t.length()) {
return false;
}
HashMap<Character, Character> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char sChar = s.charAt(i);
char tChar = t.charAt(i);
if (map.containsKey(sChar)) {
if (map.get(sChar) != tChar) {
return false;
}
} else {
if (map.containsValue(tChar)) {
return false;
}
map.put(sChar, tChar);
}
}
return true;
}