LeetCode--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.
解法一:刚开始没太理解题目重构的意思。以为是第一个字符串相同的字符位置对应第二个字符串相同位置处也要相等,于是写出了如下代码:
public class Solution { public boolean isIsomorphic(String s, String t) { if(s==null || t==null) return false; if(s.length() != t.length()) return false; char[] ss = s.toCharArray(); char[] tt = t.toCharArray(); boolean flag = false; for(int i=0; i<ss.length; i++){ for(int j=i+1; j<ss.length; j++){ if(ss[i]==ss[j]){ flag = true; if(tt[i]!=tt[j]) return false; } } } if(flag==true) return true; else return false; } }
提交后显示时间超时。于是Google之,原来这里说的重构是指第一个串的某个字符映射第二个串的某一字符,只能映射一个“All occurrences of a character must be replaced with another character while preserving the order of characters.” 。都是没好好读题惹的祸....但是后来想了一下,自己的解法也有一定道理。相同的字符处是否一致不就是相同的映射麽。。
解法二:用哈希表表示映射关系。第一遍,用s的每个char作为key,映射的t的char作为value,如果出现一个不匹配,则返回false;第二遍,用t的每个char作为key,映射的s的char作为value,同样,如果一旦出现不匹配或者多个映射,则返回false;若直到程序最后都没有返回值,则说明两个串同构,返回true。
HashMap h1 = new HashMap<Character, Character>(); char[] ss = s.toCharArray(); char[] tt = t.toCharArray(); for(int i=0; i<ss.length; i++){ if(!h1.containsKey(ss[i])) h1.put(ss[i], tt[i]); else{ if( !h1.get(ss[i]).equals(tt[i])) return false; } } HashMap h2 = new HashMap<Character, Character>(); for(int i=0; i<tt.length; i++){ if(!h2.containsKey(tt[i])) h2.put(tt[i], ss[i]); else{ if(!h2.get(tt[i]).equals(ss[i])) return false; } } return true;