205. Isomorphic Strings - Easy
阿新 • • 發佈:2018-12-03
ret == style with note boolean turn spa mine
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.
Example 1:
Input: s ="egg",
t ="add"
Output: true
Example 2:
Input: s ="foo",
t ="bar"
Output: false
Example 3:
Input: s ="paper",
t ="title"
Output: true
Note:
You may assume both s and t have the same length.
用hashmap,key是s[i],value是t[i]
註意:如果map中已經存在s[i]這個key,不能再更新其value;由於一個value也只能對應一個key,如果map中已經存在s[i]對應的value,則無法添加新的映射到value的key
時間:O(N),空間:O(N)
class Solution { public boolean isIsomorphic(String s, String t) { HashMap<Character, Character> map = new HashMap<>(); for(int i = 0; i < s.length(); i++) { if(map.containsKey(s.charAt(i)) && map.get(s.charAt(i)) == t.charAt(i))continue; else if(!map.containsValue(t.charAt(i)) && !map.containsKey(s.charAt(i))) map.put(s.charAt(i), t.charAt(i)); else return false; } return true; } }
205. Isomorphic Strings - Easy