JAVA---------------Easy Version To UnderStand!!!!!!!


  • 0
    H
    public boolean wordPattern(String pattern, String str) {
    	if (str == null || pattern == null)
    		return false;
    	String[] words = str.split(" ");
    	HashMap<Character, String> map1 = new HashMap<Character, String>();
    	HashMap<String, Character> map2 = new HashMap<String, Character>();
    	int pattern_len = pattern.length(), str_len = words.length;
    	if (pattern_len != str_len)
    		return false;
    	for (int i = 0; i < pattern_len; i++) {
    		if (map1.get(pattern.charAt(i)) == null)
    			map1.put(pattern.charAt(i), words[i]);
    		else {
    			if (!map1.get(pattern.charAt(i)).equals(words[i]))
    				return false;
    		}
    	}
    	for (int i = 0; i < pattern_len; i++) {
    		if (map2.get(words[i]) == null)
    			map2.put(words[i], pattern.charAt(i));
    		else {
    			if (!map2.get(words[i]).equals(pattern.charAt(i)))
    				return false;
    		}
    	}
    	return true;
    }

Log in to reply
 

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