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.
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.
以s中的每个字符作为key,t中的每个字符作为value,利用Java中的map容器做映射。
public class Solution {
public boolean isIsomorphic(String s, String t) {
Map<Character,Character> mp1 = new HashMap<>();
final int len1 = s.length();
final int len2 = s.length();
if(len1!=len2) return false;
if(len1==0) return true;
for(int i = 0;i < len1;i++)
{
if(!mp1.containsKey(s.charAt(i)))
{
mp1.put(s.charAt(i),t.charAt(i));
for(int j = 0;j<i;j++)
{
if(mp1.get(s.charAt(i))==mp1.get(s.charAt(j)))//多对一
{
return false;
}
}
}
else
{
if(mp1.get(s.charAt(i))!=t.charAt(i))//一对多
{
return false;
}
}
}
return true;
}
}
时间复杂度较高,期待更高效的方法。