-
Notifications
You must be signed in to change notification settings - Fork 0
205. Isomorphic Strings
Jacky Zhang edited this page Aug 17, 2016
·
1 revision
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.
String类题目。 解题思路为记下各字符所在的位置,若两个string对应字符出现的位置不能对应,则不是isomorphic,返回false。 若字符只有ASCII码,则可用长度为128的固定数组,否则通用解法为采用hash map。
public class Solution {
public boolean isIsomorphic(String s, String t) {
if(s.length() != s.length()) return false;
int[] sAddr = new int[128];
int[] tAddr = new int[128];
for(int i = 0; i < s.length(); i++) {
if(sAddr[s.charAt(i)] != tAddr[t.charAt(i)]) {
return false;
}
sAddr[s.charAt(i)] = i+1;
tAddr[t.charAt(i)] = i+1;
}
return true;
}
}