Simple Java Solution beats 79%


  • 0
    R
    public class Solution {
        public boolean wordPattern(String pattern, String str) 
        {
            HashMap<Character,String> mappings = new HashMap<>(); 
            
            String[] words = str.split(" "); 
            char[] patternLetters = pattern.toCharArray(); 
            
            if(words.length != patternLetters.length)
                return false; 
            
            for(int i = 0; i < patternLetters.length; i++)
            {
                if(mappings.get(patternLetters[i]) != null && !mappings.get(patternLetters[i]).equals(words[i]))
                    return false; 
                else if(mappings.get(patternLetters[i]) == null && mappings.containsValue(words[i]))
                    return false; 
                else
                    mappings.put(patternLetters[i], words[i]); 
            }
                
            return true; 
        }
    }

Log in to reply
 

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