Simple HASHMAP SOLUTION


  • 0
    A
    public boolean wordPattern(String pattern, String str) {        
        
        String st[] = str.split(" ");
        if(st.length!=pattern.length()){
            return false;
        }
        Map<Character,String> map = new HashMap<>();
        for(int i = 0; i < st.length; i++){
            
            if(map.containsKey(pattern.charAt(i))){
                if(!map.get(pattern.charAt(i)).equals(st[i])){
                    return false;
                }
            }
            //Value exists but not the key
            else if(map.containsValue(st[i]) && !map.containsKey(pattern.charAt(i))){
                    return false;
                }
            else{
                map.put(pattern.charAt(i),st[i]);
            }
        }
        return true;
    }

  • 0

    Simple hashset solution, only check if a element appear at same time.

    public class Solution {
       public boolean wordPattern(String pattern, String str) {
            
            String[] words = str.split(" ");
            
            if(pattern.length() != words.length){
                return false;
            }
            
            Set<Character> appearanceRecordPattern = new HashSet();
            Set<String> appearanceRecordWords = new HashSet();
            
            for(int i=0;i<pattern.length();i++){
                if(appearanceRecordPattern.add(pattern.charAt(i)) != appearanceRecordWords.add(words[i])){
                    return false;
                }
            }
            
            return true;
        }
    }

  • 0
    W

    this will fail with test case:"aba","cat dog dog"


Log in to reply
 

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