Easy java solution with comments beats 70%


  • 2
    D

    public class Solution {
    public boolean wordPattern(String pattern, String str) {

        //Base case: if both are null, return true
        if(pattern==null && str==null)
            return true;
            
        //if either are null, return false
        if(pattern==null || str==null)
            return false;
            
        
        //Hashmap to store character, string pair
        HashMap<Character,String> map=new HashMap<Character,String>();
        
        String[] words=str.split(" ");
        
        //if lengths are not equal, return false
        if(words.length != pattern.length())
            return false;
            
        for(int i=0;i<words.length;i++)
        {
            //if key, is not present, execute the following
            if(!map.containsKey(pattern.charAt(i)))
            {
                //check that the value has not been used before
                if(map.containsValue(words[i]))
                    return false;
                
                //if not present, enter value in the map
                map.put(pattern.charAt(i),words[i]);
            }
            else
            {
                //check to see if current values match
                String temp=map.get(pattern.charAt(i));
                
                if(temp.equals(words[i]))
                    continue;
                else
                    return false;
            }
        }
        
        //return true if everything is satisfied
        return true;
            
        
        
        
    }
    

    }


Log in to reply
 

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