*205. Isomorphic Strings (string & map idea)
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.
Example 1:
Input: s ="egg",
t ="add"
Output: true
Example 2:
Input: s ="foo",
t ="bar"
Output: false
Example 3:
Input: s ="paper",
t ="title"
Output: true
Note:
You may assume both s and t have the same length.
Accepted solution:
create an array: map all the character and count the value as the index of each characters in string. start from 1
e.g.: egg & dda & add
a['e'] = 1 a['g'] = 2 -> 3 ; a['d'] = 1 -> 2 a['a'] 3 ; a['a'] = 1 a['d'] 2 -> 3
class Solution { public boolean isIsomorphic(String s, String t) { //letter , index of string //e.g. egg : e: 1 g:2 g:3 if(s.length()!=t.length()) return false; int[] a = new int[256]; int[] b = new int[256]; for(int i = 0; i<s.length(); i++){ if(a[s.charAt(i)] != b[t.charAt(i)]) return false; //update the character a[s.charAt(i)] = i+1; // why plus 1 for the case aa & ab b[t.charAt(i)] = i+1; } return true; } }
Good idea make the code clean and easy. Think before coding.