Simple java solution


  • 0
    H
    public boolean wordPattern(String pattern, String str) {
        HashSet<Character> set = new HashSet<>();
        HashSet<String> set2 = new HashSet<>();
        String[] part = str.split("\\s+");
        if (pattern.length() != part.length) {return false;}
        for (int i = 0; i < pattern.length(); i++) {
            if (set.contains(pattern.charAt(i))) {
                if (!set2.contains(part[i])) {return false;}
                set.remove(pattern.charAt(i));
                set2.remove(part[i]);
            } else {
                if (set2.contains(part[i])) {return false;}
                set.add(pattern.charAt(i));
                set2.add(part[i]);
            }
        }
        return true;
    }
    

    It's very straightforward, but the drawback is 2n space.


  • 0
    A

    optimise plz..Instead of using 2 HashMap , try using 2 HashSet.


  • 0
    H

    thank you for reminding. I have edited it.


Log in to reply
 

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