Simple Java Solution


  • 0
    Z
    public class Solution {
        public boolean wordPattern(String pattern, String str) {
            HashMap hash = new HashMap();
            String[] words = str.split(" ");
            
            if(words.length != pattern.length())
                return false;
                
            for(int i=0; i< pattern.length(); i++){
                char c = pattern.charAt(i);
                
                if(hash.containsKey(c) && !hash.get(c).equals(words[i]))
                    return false;
                
                if(!hash.containsKey(c) && hash.containsValue(words[i]))
                    return false;
                
                hash.put(c, words[i]);
                
            }
            
            return true;
        }
    }
    '''

Log in to reply
 

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