public class Solution { public boolean isIsomorphic(String s, String t) { /* Metho1: // special case if ( s== null || t == null ) { return false; } if ( s.length() != t.length() ) { return false; } if ( s.length() ==0 && t.length() == 0 ) { return true; } HashMapmap = new HashMap (); for ( int i = 0; i < s.length();i++ ) { char c1 = s.charAt(i); char c2 = t.charAt(i); //Input: // "ab", "aa" //Output: //true //Expected: //false // **** Need to backward check //if ( map.containsKey(c1) ) //{ // if ( c2 != map.get(c1) ) // { // return false; // } //} //else //{ // map.put(c1,c2); //} Character c = getKey(map,c2); if ( c != null && c != c1) { return false; } else if ( map.containsKey(c1) ) { if ( c2 != map.get(c1) ) { return false; } } else { map.put(c1,c2); } } return true; */ /*Method2:*/ if ( s.length() != t.length() ) { return false; } if ( s.length() == 0 && t.length() == 0) { return true; } if ( s == null || t == null ) { return false; } HashMap map1 = new HashMap (); HashMap map2 = new HashMap (); for ( int i = 0 ;i < s.length() ;i ++) { char c1 = s.charAt(i); char c2 = t.charAt(i); if ( map1.containsKey(c1) ) { if ( map1.get(c1) != c2 ) { return false; } } if ( map2.containsKey(c2) ) { if ( map2.get(c2) != c1 ) { return false; } } map1.put( c1,c2 ); map2.put( c2,c1); } return true; } // a method for getting key given a target value // a method for getting key of a target value private Character getKey(HashMap map, Character value ) { for ( Map.Entry entry : map.entrySet() ) { if ( entry.getValue().equals(value) ) { return entry.getKey(); } } return null; } }
Wednesday, July 8, 2015
[Leetcode]07/08 [hash] Isomorphic Strings
/*
Method1:
Time:O(n^2); Space:O(n)
Logic:
check each correpsonding character set if in the map
and backward check if
the corresponding key of c2 is the same as current c1
getKey()
Method2:
Time:O(n):Space:O(2n)
Logic:
Two hashmap
sourceMap[ t[x] ] = s[x]
targetMap[ s[x] ] = t[x]
False if two map relationship valid;Otherwise, it is ture.
Given "egg", "add", return true.
Given "foo", "bar", return false.
Given "paper", "title", return true.
*/
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment