java solution using map


  • 0
    P
    class Solution {
        public boolean wordPattern(String pattern, String str) {
            
           
            String[] s = str.split(" ");
            
            if (s.length != pattern.length()){
                return false;
            }
            
            Map<String,String> map = new HashMap<>();
            
            for (int i=0; i<s.length;i++){
                
                String value = map.get(Character.toString(pattern.charAt(i)));
                if (value==null){
                    
                    if (map.containsValue(s[i])){
                        return false;
                    }
                     map.put(Character.toString(pattern.charAt(i)),s[i]);
                }
                else if (!value.equals(s[i])){
                    return false;
                }
            }
            return true;
            
        }
    }

Log in to reply
 

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