1ms Java solution with simple data structure


  • -1
    public class Solution {
        public boolean wordPattern(String pattern, String str) {
            String[] s = new String[26];
            String[] newstr = str.split(" ");
            Set<String> set = new HashSet<>();
            if (pattern.length() != newstr.length){
                return false;
            }
            for(int i = 0; i < pattern.length(); i++){
                if (s[pattern.charAt(i) - 'a'] == null){
                    s[pattern.charAt(i) - 'a'] = newstr[i];
                    if(!set.add(newstr[i])){
                        return false;
                    }
                }else if(!s[pattern.charAt(i) - 'a'].equals(newstr[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.