Java simple and self-explainable solution


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