0205. Isomorphic Strings - kumaeki/LeetCode GitHub Wiki
Given two strings s and t, determine if they are isomorphic.
Two strings s and t 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
Constraints:
- 1 <= s.length <= 5 * 10^4
- t.length == s.length
- s and t consist of any valid ascii character.
解法1
判断s和t中的字符是否是一一对应, 没有多对一的情况. 那么判断两次就好了.
class Solution {
public boolean isIsomorphic(String s, String t) {
if(s.length() != t.length())
return false;
return helper(s, t) && helper(t, s);
}
private boolean helper(String s, String t){
Map<Character, Character> map = new HashMap<>();
for(int i = 0, len = s.length(); i < len; i++){
char cs = s.charAt(i), ct = t.charAt(i);
if(!map.containsKey(cs))
map.put(cs, ct);
else if(map.get(cs) != ct)
return false;
}
return true;
}
}