205. Isomorphic Strings
Given two strings s
and t
, determine if they are isomorphic.
Two strings s
and t
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
Constraints:
1 <= s.length <= 5 * 104
t.length == s.length
s
andt
consist of any valid ascii character.
My Solutions:
方法1:
建立sm和tm两个map,对s和t里的每一个字母,必须在另一个map里相互对应。比如sm[e] = a, tm[a] = e.
方法2:
map里不储存字母,而是储存出现的index。s和t里出现的对应字母应该index相同。
public class Solution {
public boolean isIsomorphic(String s, String t) {
// char[] s = sString.toCharArray();
// char[] t = tString.toCharArray();
// int length = s.length;
// if(length != t.length) return false;
// char[] sm = new char[256];
// char[] tm = new char[256];
// for(int i=0; i<length; i++){
// char sc = s[i];
// char tc = t[i];
// if(sm[sc] == 0 && tm[tc] == 0){
// sm[sc] = tc;
// tm[tc] = sc;
// }else{
// if(sm[sc] != tc || tm[tc] != sc){
// return false;
// }
// }
// }
// return true;
int[] mapS= new int[256], mapT = new int[256];
int len = s.length();
for (int i = 0; i < len; i++) {
if (mapS[s.charAt(i)] != mapT[t.charAt(i)]) return false;
mapS[s.charAt(i)] = i + 1;
mapT[t.charAt(i)] = i + 1;
}
return true;
}
}
Last updated