Easy
829240FavoriteShare
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.
C++:
/*
* @Author: SourDumplings
* @Date: 2019-08-18 09:40:41
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/isomorphic-strings/
*/
class Solution
{
public:
bool isIsomorphic(string s, string t)
{
int l = s.length();
if (l != t.length())
{
return false;
}
map<char, char> m1, m2;
for (int i = 0; i < l; i++)
{
if (m1.find(s[i]) == m1.end())
{
if (m2.find(t[i]) != m2.end())
{
return false;
}
m1[s[i]] = t[i];
m2[t[i]] = s[i];
}
else
{
if (m1[s[i]] != t[i])
{
return false;
}
}
}
return true;
}
};
Java:
import java.util.Hashtable;
import java.util.Map;
/*
* @Author: SourDumplings
* @Date: 2019-08-18 10:00:02
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/isomorphic-strings/
*/
class Solution
{
public boolean isIsomorphic(String s, String t)
{
int l = s.length();
if (l != t.length())
{
return false;
}
Map<Character, Character> m1 = new Hashtable<>();
Map<Character, Character> m2 = new Hashtable<>();
for (int i = 0; i < l; i++)
{
Character c1 = s.charAt(i);
Character c2 = t.charAt(i);
if (m1.containsKey(c1))
{
if (m1.get(c1) != c2)
{
return false;
}
}
else
{
if (m2.containsKey(c2))
{
return false;
}
m1.put(c1, c2);
m2.put(c2, c1);
}
}
return true;
}
}