Java solution


  • 0
    S
    public boolean wordPattern(String pattern, String str) {
            char[] charsInPattern = pattern.toCharArray();
            String[] words = str.split(" ");
            if(charsInPattern.length != words.length){
                return false;
            }
            int[] patternCharCount = new int[26];
            for(int i = 0 ; i < charsInPattern.length ; i++ ){
                patternCharCount[charsInPattern[i] - 'a']++;
            }
            Map<String, Integer> wordCount = new HashMap<>();
            for(String word : words){
                if(wordCount.containsKey(word)){
                    wordCount.put(word, wordCount.get(word)+1);
                }else {
                    wordCount.put(word, 1);
                }
            }
            for(int i = 0 ; i < charsInPattern.length ; i++){
                if(patternCharCount[charsInPattern[i]-'a']!= wordCount.get(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.