205. Isomorphic Strings

来源:互联网 发布:win7网络打印机找不到 编辑:程序博客网 时间:2024/05/17 23:32

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.

public class Solution {/* * 思路:利用一个Map来辅助解决问题,Map的key为s中的字符,Map的value为t中与之对应的字符 * 循环遍历s(题目中已经假设s和t长度相同),  * 如果遍历到的字符在Map中存在,则检测它对应的value * 是否为t中对应的字符,是则继续,不是则直接返回false; * 如果遍历到的字符在Map中不存在,先检测Map的vlaue中是否包含t对应的字符,如果包含 * 直接返回false,如果不包含,则将s,t中对应的字符put进Map *  */public boolean isIsomorphic(String s, String t) {if (s==null || s.length()<=1) {return true;}Map<Character, Character> map = new HashMap<Character, Character>();for (int i=0; i<s.length(); i++) {Character a = s.charAt(i);Character b = t.charAt(i);if (map.containsKey(a)) {if (map.get(a).equals(b)) {continue;} else {return false;}} else {if (!map.containsValue(b)) {map.put(a, b);} else {return false;}}}return true;}}