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.
分析
- simplify new HashMap<Character, Character> to new char[256] here. why 256? There are 256 ASCII characters. This includes standard ASCII characters(0-127) and Extended ASCII characters(128-255)
- traverse the whole string s (or t, because 's and t have the same length'), using two pointers: a, b to check (1)whether character a has marked, if no, mark it to b ; if yes, check whether it equals to b (2) whether character b has marked, if no, mark it to a ; if yes, check whether it equals to a
- why we should check twice ? Take s: bar t:foo for example, it works from s to t; but doesn't work from t to s
解题
class Solution {
public boolean isIsomorphic(String s, String t) {
if(s.length()!=t.length()) return false;
char [] mapAB = new char[256];
char [] mapBA = new char[256];
for(int i = 0; i<s.length();i++){
char a = s.charAt(i);
char b = t.charAt(i);
if(mapAB[a]!=0){
if(mapAB[a]!=b) return false;
}else{
mapAB[a]= b;
}
if(mapBA[b]!=0){
if(mapBA[b]!=a) return false;
}else{
mapBA[b]=a;
}
}
return true;
}
}