Java simple solution WITH " explanation "


  • 0
    O
    String []str2=str.split(" ");
     // check if the number of characters of the pattern is equal to the number of words u have .
    	        if(pattern.length()!=str2.length)return false;
    // the first HashMap stores each character with the attached word.
    
    	        HashMap<Character,String>x=new HashMap<Character,String>();
    //the second HashMap is to check if the word was attached to another character or not
    
    	        HashMap<String,String>y=new HashMap<String,String>();
    	        
    	        for (int i = 0; i < str2.length; i++) {
    				if(x.containsKey(pattern.charAt(i))){
    					if(!str2[i].equals(x.get(pattern.charAt(i))))return false;
    				}
    				else 
    					{
    					if(y.containsKey(str2[i]))return false;
    					else{
    					x.put(pattern.charAt(i), str2[i]);
    					y.put(str2[i], "bo");
    					}
    					}
    					
    			}
    	        return true;

  • 0
    E

    the second hashmap could just be hashset


Log in to reply
 

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