Java solution using map and set


  • 0
    K

    First use the Map to check if the current character is already in use. The check using the Set if there is more than one mapping for a given word.

    public boolean wordPattern(String pattern, String str) {
            Map<Character, String> patMap = 
                new HashMap<Character,String>();
            Set<String> strSet = new HashSet<String>();
            String[] bagOfWords = str.split("\\s+");
            int patSize = pattern.length();
            int strSize = bagOfWords.length;
            
            if(patSize != strSize) {
                return false;
            }
            
            for(int i = 0; i < patSize; i++) {
                Character currChar = pattern.charAt(i);
                String currStr = bagOfWords[i];
                
                if(patMap.containsKey(currChar)) {
                    String retrieved = patMap.get(currChar);
                    if(!retrieved.equals(currStr)) {
                        return false;
                    }
                } else {
                    patMap.put(currChar, currStr);
                }
            }
            
            for(String currStr : patMap.values()) {
                if(!strSet.add(currStr)) {
                    return false;
                }
            }
            return true;
        }
    

  • 1

    @kolygri Hi! Could you please format your code properly by surrounding your code with 3 backticks?

    Like this:

    ```
    Your code here
    ```

  • 0
    K

    Yeah sure, no problem :)


Log in to reply
 

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