HashMap Java Solution


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

Log in to reply
 

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