Accepted Java solution. O(n) time and using Hashmap


  • 1
    C
    public class Solution {
        public boolean isIsomorphic(String s, String t) {
            if(s.length()!=t.length()){
                return false;
            }
          //to check case like "ab" "aa". Need to replace key&value and check it again.
            return checkIsomorphic(s,t)&&checkIsomorphic(t,s);
            
        }
        
        private boolean checkIsomorphic(String s, String t) {
            HashMap<Character,Character> occMap = new HashMap<Character,Character>();
            for(int i=0;i<s.length();i++){
                char cs = s.charAt(i);
                char ct = t.charAt(i);
                if(!occMap.containsKey(cs)){
                    occMap.put(cs, ct);
                }else{
                    char val1 = occMap.get(cs);
                    if(ct!=val1)
                        return false;
                }
            }
            return true;
        }
    }

Log in to reply
 

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