本文共 1984 字,大约阅读时间需要 6 分钟。
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.
public class Solution { public boolean isIsomorphic(String s, String t) { Mapmap = new HashMap<>(); Set keyset; for (int i = 0; i < s.length(); i++) { keyset = map.keySet(); if (keyset.contains(s.charAt(i))) { List list = map.get(s.charAt(i)); list.add(i); map.put(s.charAt(i), list); } else { List list = new ArrayList<>(); list.add(i); map.put(s.charAt(i), list); } } keyset = map.keySet(); Iterator ite = keyset.iterator(); while (ite.hasNext()) { Character tmp = (Character) ite.next(); List list = map.get(tmp); if (list.size() > 1) { Integer val = list.get(0); for (int i = 1; i < list.size(); i++) { if (t.charAt(val) != t.charAt(list.get(i))) return false; } } } // 交换s t 重新来一遍 map.clear(); keyset.clear(); for (int i = 0; i < t.length(); i++) { keyset = map.keySet(); if (keyset.contains(t.charAt(i))) { List list = map.get(t.charAt(i)); list.add(i); map.put(t.charAt(i), list); } else { List list = new ArrayList<>(); list.add(i); map.put(t.charAt(i), list); } } keyset = map.keySet(); ite = keyset.iterator(); while (ite.hasNext()) { Character tmp = (Character) ite.next(); List list = map.get(tmp); if (list.size() > 1) { Integer val = list.get(0); for (int i = 1; i < list.size(); i++) { if (s.charAt(val) != s.charAt(list.get(i))) return false; } } } return true; }}
转载地址:http://tvuni.baihongyu.com/