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.
题目大意:判断两个相等长度的字符串是不是isomorphic,isomorphic的定义就是一个字符串的每个字符可以一一映射得到另一个字符串
思路:可以用一个hashmap来存储对应字符的映射关系,但是要注意映射是一对一,不能多对一,不能一对多
public class Solution { public boolean isIsomorphic(String s, String t) { Map<Character, Character> mapping = new HashMap<>(); for (int i = 0; i < s.length(); i++) { char a = s.charAt(i); char b = t.charAt(i); if (mapping.containsKey(a)) { if (mapping.get(a) != b) { return false; } } else if (mapping.containsValue(b)) { return false; } else { mapping.put(s.charAt(i), t.charAt(i)); } } return true; } }
也可以用两个256大小的数组来标记关系

浙公网安备 33010602011771号