Q-26 Isomorphic Strings - LeetCode

PHOTO EMBED

Thu Jan 26 2023 12:09:03 GMT+0000 (Coordinated Universal Time)

Saved by @Ayush_dabas07

class Solution {
    public boolean isIsomorphic(String s, String t) {
        if(s.length()==1)return true;
        
        if(s.length()!=t.length())
        return false;

//make frequency map and map characters 



        HashMap<Character,Character> map = new HashMap<>();

        for(int i = 0; i< s.length();i++){
            char ch1 = s.charAt(i);
            char ch2 = t.charAt(i);

            if(map.containsKey(ch1)){
                //if new and old mapped characters are not equal
                if(map.get(ch1) != ch2)
                return false;
            }
            //if map doesn't contains key
            else{
                
                //but map contains value 
                if(map.containsValue(ch2))
                return false;
                
                map.put(ch1 , ch2);
                
            }
        }

        return true;
    }
}
content_copyCOPY

https://leetcode.com/problems/isomorphic-strings/