Leetcode.205 Isomorphic Strings(Java)
Leetcode.205 Isomorphic Strings
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.
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
Note:
You may assume both *s* and *t* have the same length.
Solution
双hashmap
两个都是字符串,作比较的是单个字符,如果未经处理直接存在一个表中可能会产生冲突
“ab”
"aa"
因此先考虑存入两个表(防止互相干扰)
class Solution {
/*
time:O(n)
space:O(n)
*/
public boolean isIsomorphic(String s, String t) {
int[] sIndex = new int[256];
int[] tIndex = new int[256];
if(s.length() != t.length()){
return false;
}
for(int i=1;i<s.length()+1;i++){
//"aee" "aee"
if(sIndex[s.charAt(i-1)] != tIndex[t.charAt(i-1)]){
return false;
}
sIndex[s.charAt(i-1)] = i;
tIndex[t.charAt(i-1)] = i;
}
return true;
}
}
代码17,18行由于初始化是0,所以索引从1开始,防止0冲突
单hashmap
class Solution {
/*
time:O(n)
space:O(n)
*/
public boolean isIsomorphic(String s, String t) {
int[] index = new int[512];
if(s.length() != t.length()){
return false;
}
for(int i=0;i<s.length();i++){
//"aee" "aee"
if(index[s.charAt(i)] != index[t.charAt(i)+256]){
return false;
}
index[s.charAt(i)] = i+1;
index[t.charAt(i)+256]=i+1;
}
return true;
}
}
爱生活、爱编程