Easy Java solution based on two HashMaps


  • 0
    O
    public class Solution {
        public boolean wordPattern(String pattern, String str) {
            HashMap<Character, String> pMap = new HashMap<Character, String>();
            HashMap<String, Character> sMap = new HashMap<String, Character>();
            String[] words = str.split(" ");
            if (words.length != pattern.length()) {
                return false;
            }
            char ch;
            for(int i = 0; i < pattern.length(); i++) {
                ch = pattern.charAt(i);
                if (pMap.containsKey(ch) && !words[i].equals(pMap.get(ch))) {
                    return false;	
                } 
                if (sMap.containsKey(words[i]) && sMap.get(words[i]) != ch) {
                	return false;
                }
                pMap.put(ch, words[i]);
                sMap.put(words[i], ch);
            }
            return true;
        }
    }
    

Log in to reply
 

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