290. Word Pattern

290. Word Pattern

class Solution {
    public boolean wordPattern(String pattern, String s) {
        HashMap<Character,String> map = new HashMap<>();
        String[] sWords = s.split(" ");
        if(sWords.length != pattern.length()) return false;
        for(int i = 0; i < pattern.length(); i++){
            for (Map.Entry<Character, String> entry : map.entrySet()) {
                if(entry.getValue().equals(sWords[i]) && entry.getKey() != pattern.charAt(i)) return false;
                 if(!entry.getValue().equals(sWords[i]) && entry.getKey() == pattern.charAt(i)) return false;
            }
                 map.put(pattern.charAt(i),sWords[i]);

        }
        return true;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s