1. 題目描述
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.
給定兩個字符串,判斷兩個字符串是不是同構的。
2. 解題思路
這個題目和 [290] Word Pattern很相似,只不過290題將一個字符串看做一個模式,判斷同構性,而本題是講一個字符看做一個模式判斷同構性。本次的解法和290題略有不同,但是基本思路都是一樣的。需要兩個數據結構,一個數據結構去保存從s到t中的字符的映射關係,另一個數據結構去保存是否這個已經被映射過,如s爲aab,而t爲ccc,他們的模式是不同的,因爲a已經映射到c,所以b不能再被映射到c。
3. Code
public class Solution {
public boolean isIsomorphic(String s, String t) {
// character是否只是ascii字符?
int [] maps = new int[256]; // s中的值映射到t中的哪一個
boolean [] isMapped = new boolean[256]; // 是否已經被map了
for(int i = 0; i < s.length(); ++i)
{
int svalue = (int)s.charAt(i);
int mapPos = maps[svalue]; // mapp的字符位置
// 如果不是初始值0,這個判斷捨去了ascii碼的第一個null,實測不影響
if(mapPos != 0)
{
if(mapPos != (int)t.charAt(i)) return false;
}else{
int tvalue = (int)t.charAt(i);
if(isMapped[tvalue]) return false;
maps[svalue] = tvalue;
isMapped[tvalue] = true;
}
}
return true;
}
}