Using 2 maps in Java


  • 0
    L

    Should be easier with using 2 boolean arrays as well.

    public boolean isIsomorphic(String s, String t) {
            if(s.length()!=t.length()) {
                return false;
            }
            
            Map<Character,Character> forwardmap = new HashMap<>();
            Map<Character,Character> reversemap = new HashMap<>();
            for(int i=0;i<s.length();i++) {
                if(forwardmap.containsKey(s.charAt(i)) && forwardmap.get(s.charAt(i))!=t.charAt(i)) {
                    return false;
                }
                if(reversemap.containsKey(t.charAt(i)) && reversemap.get(t.charAt(i))!=s.charAt(i)) {
                    return false;
                }
                forwardmap.put(s.charAt(i),t.charAt(i));
                reversemap.put(t.charAt(i),s.charAt(i));
            }
            
            return true;
        }
    

Log in to reply
 

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