首页 > 代码库 > Isomorphic Strings
Isomorphic Strings
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.
这题需要注意的地方是我们要从S到T 和T到S都检查一遍。
1 public class Solution { 2 public boolean isIsomorphic(String s, String t) { 3 if (s.length() != t.length()) return false; 4 5 Map<Character, Character> map = new HashMap<>(); 6 7 for (int i = 0; i < s.length(); i++) { 8 char chKey = s.charAt(i); 9 char chValue =http://www.mamicode.com/ t.charAt(i); 10 11 if(map.containsKey(chKey)) { 12 char value = http://www.mamicode.com/map.get(chKey); 13 if (value != chValue) { 14 return false; 15 } 16 } else { 17 map.put(chKey, chValue); 18 } 19 } 20 21 map.clear(); 22 23 for (int i = 0; i < s.length(); i++) { 24 char chKey = t.charAt(i); 25 char chValue =http://www.mamicode.com/ s.charAt(i); 26 27 if(map.containsKey(chKey)) { 28 char value = http://www.mamicode.com/map.get(chKey); 29 if (value != chValue) { 30 return false; 31 } 32 } else { 33 map.put(chKey, chValue); 34 } 35 } 36 37 return true; 38 } 39 }
Isomorphic Strings
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。