Simple java solution beats 95%


  • 0
    L

    The solution is self explanatory.

     public boolean wordPattern(String pattern, String str) {
            String[] split = str.split(" ");
            if(split.length != pattern.length())
                return false;
            int[] num = new int[26];
            for(int i =0;i < 26;i++)
                num[i] = -1;
            HashSet<String> visited = new HashSet<>();
            for(int i =0; i < pattern.length();i++){
                if(num[pattern.charAt(i) - 'a'] == -1){
                    if(visited.contains(split[i]))
                        return false;
                    num[pattern.charAt(i) - 'a'] = i;
                    visited.add(split[i]);
                }
                else{
                    if(!split[i].equals(split[num[pattern.charAt(i) - 'a']]))
                        return false;
                    
                }
            }
            return true;
        }
    

Log in to reply
 

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