Short Concise Java Solution


  • 0
    Y
     String[] s = str.split(" ");
            if(s.length!=pattern.length()) return false;
            Map<Character, String> m1 = new HashMap<Character, String>();
            Map<String, Character> m2 = new HashMap<String, Character>(); 
            
            for(int i=0;i<pattern.length();i++){
                if(m1.containsKey(pattern.charAt(i))){
                    if(!m1.get(pattern.charAt(i)).equals(s[i])) return false;
                }else{
                    if(m2.containsKey(s[i])) return false;
                    else {
                        m1.put(pattern.charAt(i),s[i]);
                        m2.put(s[i],pattern.charAt(i));
                    }
                    
                }
            }
            return true;
        }
    

Log in to reply
 

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