Java Solution using HashMap


  • -1
    C
    public class Solution {
        public boolean isIsomorphic(String s, String t) {
            char arr1[]=s.toCharArray();
            char arr2[]=t.toCharArray();
            if(arr1.length != arr2.length)
            return false;
            else if( arr1 == null && arr2 == null)
            return true;
            else if(arr1.length == 0)
            return true;
            else
            {
            int i;
            char ch1,ch2;
            HashMap<Character,Character> map = new HashMap<Character,Character>();
            map.put(arr1[0],arr2[0]);
            for(i=1;i<arr1.length;i++)
            {
                ch1=arr1[i];
                ch2=arr2[i];
                if(map.containsKey(ch1))
                {
                    if(map.get(ch1) != ch2)
                    return false;
                }
                else if(map.containsValue(ch2))
                {
                    if(map.get(ch1) == null || map.get(ch1) != ch2)
                    return false;
                }
                else
                map.put(ch1,ch2);
            }
            return true;
            }
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.