98% JAVA solution using String array and Set


  • 0
    G
    public class Solution {
        public boolean wordPattern(String pattern, String str) {
            if(pattern == null || str == null){
                return false;
            }
            String[] list = str.trim().split(" ");
            String[] map = new String[26];
            Set<String> set = new HashSet<>();
            if(pattern.length() != list.length){
                return false;
            }
            int len = list.length;
            for(int i = 0; i < len; i++){
                int key = pattern.charAt(i) - 'a';
                String value = list[i];
                if(map[key] == null){
                    map[key] = value;
                    if(set.contains(value)){
                        return false;
                    }
                    set.add(value);
                }
                if(!map[key].equals(value)){
                    return false;
                }
            }
            return true;
        }
    }
    

Log in to reply
 

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