【题目】
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.
【思路】
用一个hashmap, key是s的元素,value是t得元素。
对于每一个a,b。
如果map含有a,那么如果a在map里记录的值等于b,那么继续,否则返回false.
如果不含有a,而且b也不在map的值群里面。那么就放入新值对a,b,否则b在value群中,说明a,b,不配对,返回false.
【代码】
用到hashtable
public class Solution {
public boolean isIsomorphic(String s, String t) {
if(s == null || s.length() <= 1) return true;
HashMap<Character, Character> map = new HashMap<Character, Character>();
for(int i = 0 ; i< s.length(); i++){
char a = s.charAt(i);
char b = t.charAt(i);
if(map.containsKey(a)){
if(map.get(a).equals(b))
continue;
else
return false;
}else{
if(!map.containsValue(b))
map.put(a,b);
else return false;
}
}
return true;
}
}
【方法二】
不需要hashtable
The main idea is to store the last seen positions of current (i-th) characters in both strings. If previously stored positions are different then we know that the fact they're occuring in the current i-th position simultaneously is a mistake. We could use a map for storing but as we deal with chars which are basically ints and can be used as indices we can do the whole thing with an array.
public class Solution {
public boolean isIsomorphic(String s1, String s2) {
int[] m = new int[512];
for (int i = 0; i < s1.length(); i++) {
if (m[s1.charAt(i)] != m[s2.charAt(i)+256]) return false;
m[s1.charAt(i)] = m[s2.charAt(i)+256] = i+1;
}
return true;
}
}