205. 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.
Note:
You may assume both s and t have the same length.
本题有两种方法,第一种是创建两个整型数组,然后分别遍历这两个字符串,出现过的字符,将其值变成i+1,判断两个数组值是否相等,如果不相等,则返回false。注意种方法的原理是专门针对重复元素的,对于重复元素,看其之前的值是否一样,如果不一样,则返回false;否则返回true;代码如下:
1 public class Solution { 2 public boolean isIsomorphic(String s, String t) { 3 int[] num1 = new int[256]; 4 int[] num2 = new int[256]; 5 for(int i=0;i<s.length();i++){ 6 if(num1[s.charAt(i)]!=num2[t.charAt(i)]) return false; 7 num1[s.charAt(i)] = i+1; 8 num2[t.charAt(i)] = i+1; 9 } 10 return true; 11 } 12 }
第二种解法是使用hashmap来做,hashmap里面存储的是字符对,首先遍历两个字符串,对于出现的位置i,如果map的key包括它,则比较它的值和t所对应的i的位置的值是否一样,如果一样,就是对的,否则返回false;如果不包含,则看是否包含value值,如果包含,则返回false;代码如下:
1 public class Solution { 2 public boolean isIsomorphic(String s, String t) { 3 Map<Character,Character> map = new HashMap<Character,Character>(); 4 for(int i=0;i<s.length();i++){ 5 if(map.containsKey(s.charAt(i))){ 6 if(map.get(s.charAt(i))!=t.charAt(i)){ 7 return false; 8 } 9 }else{ 10 if(!map.containsValue(t.charAt(i))) 11 map.put(s.charAt(i),t.charAt(i)); 12 else return false; 13 } 14 } 15 return true; 16 } 17 }