leetcode205- Isomorphic Strings- easy
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,分别表示s到t的字符映射和t到s的字符映射。如果出现了和以前的映射不匹配的情况,那就是不行的。
细节:1.两者长度不同的corner case 2.char的比较也要用equals不能用== 3.小心要两个hashmap,一个不够的比如"aa","ab"
实现:
class Solution { public boolean isIsomorphic(String s, String t) { if (s == null || t == null || s.length() != t.length()) { return false; } Map<Character, Character> mapA = new HashMap<>(); Map<Character, Character> mapB = new HashMap<>(); for (int i = 0; i < s.length(); i++) { Character sc = s.charAt(i); Character tc = t.charAt(i); if (mapA.containsKey(sc) && !mapA.get(sc).equals(tc) || mapB.containsKey(tc) && !mapB.get(tc).equals(sc)) { return false; } mapA.put(sc, tc); mapB.put(tc, sc); } return true; } }