Beat 98% answer. Using String array instead of HashMap.


  • 1
    I

    As said in the title. Since we only consider lowercase, most of the time we can use array to replace HashMap to get a faster performance. To avoid two indices point to the same word, I add a HashSet to store possible words in str.

    public class Solution {
        public boolean wordPattern(String pattern, String str) {
            String [] s = str.split(" ");
            if(s.length != pattern.length()) return false;
            String[] tmp = new String[26];
            HashSet<String> set = new HashSet<>();
            for (int i = 0; i < pattern.length(); i++) {
                int idx = pattern.charAt(i) - 'a';
                if(tmp[idx] != null){
                    if (!tmp[idx].equals(s[i])) {
                        return false;
                    }
                }
                else{
                    if (!set.contains(s[i])){
                        tmp[idx] = s[i];
                        set.add(s[i]);
                    }
                    
                }
            }
            int i = 0;
            while (i < pattern.length()) {
                int idx = pattern.charAt(i) - 'a';
                if (tmp[idx] == null) {
                    return false;
                }
                i++;
            }
            return true;
        }
    }
    

Log in to reply
 

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