题目: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存储对应的替换关系。
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;
}
思路二:使用数组,数组的效率普遍比哈希表快。因为一个是下标查找,一个是使用哈希值查找。
public boolean isIsomorphic2(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;
}
- Word Pattern。题目:
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
Examples:
pattern = “abba”, str = “dog cat cat dog” should return true.
pattern = “abba”, str = “dog cat cat fish” should return false.
pattern = “aaaa”, str = “dog cat cat dog” should return false.
pattern = “abba”, str = “dog dog dog dog” should return false.
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
这道题与上一题有着类似的思路,使用hashmap来存储pattern与str之间的映射关系即可。注意这里使用tmp.containsValue(ss[i])来判断双向映射条件是否满足,以防止出现上面第四个例子被漏判。
public boolean wordPattern(String pattern, String str) {
Map<Character, String> tmp = new HashMap<>();
String [] ss = str.split(" ");
if(pattern.length() != ss.length)
return false;
for(int i=0; i<pattern.length(); i++)
{
if(tmp.containsKey(pattern.charAt(i))){
if(! tmp.get(pattern.charAt(i)).equals(ss[i]))
return false;
}else if(tmp.containsValue(ss[i]))
return false;
else
tmp.put(pattern.charAt(i), ss[i]);
}
return true;
}