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
题意:
给定字符串s和t,判断能否通过字符间的一一对应关系,把前者变成后者。
思路:
既然是一一对应,用两个HashMap来解决
这里用char [] mapAB = new char[256] 作为简化版的HashMap
代码:
1 class Solution { 2 public boolean isIsomorphic(String s, String t) { 3 if(s.length()!=t.length()) return false; 4 char [] mapAB = new char[256]; 5 char [] mapBA = new char[256]; 6 for(int i = 0; i<s.length();i++){ 7 char a = s.charAt(i); 8 char b = t.charAt(i); 9 if(mapAB[a]!=0){ 10 if(mapAB[a]!=b) return false; 11 }else{ 12 mapAB[a]= b; 13 } 14 if(mapBA[b]!=0){ 15 if(mapBA[b]!=a) return false; 16 }else{ 17 mapBA[b]=a; 18 } 19 } 20 return true; 21 } 22 }