Simple and easy solution using HashMap and HashSet


  • 0

    class Solution {
    public boolean wordPattern(String pattern, String str) {
    HashMap<Character,String> hp = new HashMap<Character,String>();
    HashSet<String> hs = new HashSet<String>();
    String[] parts = str.split(" ");
    System.out.println(parts.length);
    System.out.println(pattern.length());
    if(parts.length!= pattern.length()){
    return false;
    }
    for(int i=0;i< pattern.length();i++){
    char c = pattern.charAt(i);
    String word = parts[i];
    if(!hp.containsKey(c)){
    if(hs.contains(word)){
    return false;
    }
    else{

                hp.put(c,word);
                hs.add(word);
                }
            }
            else{
                if(!hp.get(c).equals(word)){
                    return false;
                }
            }
        }
        System.out.println(hp);
        return true;
    }
    

    }


Log in to reply
 

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