导航
导航
文章目录
  1. 题目
  2. 翻译

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.

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 t ,判断它们是否是同构的。
如果 s 可以通过字符替换得到 t ,则说它们是同构的。
字符的所有出现都必须替换为另一个字符,并保持顺序。两个字符不能映射到同一个字符上,但是一个字符可以映射到自己。
例如,
给出 “egg” “add” ,返回true。
给出 “foo” “bar” ,返回false。
给出 “paper” “title” ,返回true。
注意:
你可以认为 s t 有相同长度。

与290. Word Pattern类似。
循环判断,维护两个map,分别记录s到t的字符映射,和t到s的字符映射,保证双向映射相同且唯一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
public boolean isIsomorphic(String s, String t) {
Map<Character, Character> sTot = new HashMap<Character, Character>();
Map<Character, Character> tTos = new HashMap<Character, Character>();

for (int i = 0; i < s.length(); i++) {
char sChar = s.charAt(i), tChar = t.charAt(i);

if (sTot.get(sChar) != null) {
if (sTot.get(sChar) != tChar) return false;
} else sTot.put(sChar, tChar);

if (tTos.get(tChar) != null) {
if (tTos.get(tChar) != sChar) return false;
} else tTos.put(tChar, sChar);
}

return true;
}
}