Java solution with comments


  • 0
    W
    //思路: 哈希表,对字符和单词做映射
    public boolean wordPattern(String pattern, String str) {
    	Map<Character, String> map = new HashMap<>();
    	String[] strs = str.split("\\s+");
    	if (pattern.length() != strs.length)
    		return false;
    
    	Set<String> values = new HashSet<>();
    	for (int i = 0; i < pattern.length(); i++) {
    		char key = pattern.charAt(i);
    		String value = strs[i];
    		if (map.containsKey(key)) {
    			if (!map.get(key).equals(value)) { // String比较需要用equals()!
    				return false;
    			}
    		} else {
    			if (values.contains(value)) {
    				return false; // 因为是双向映射,所以value之前不可能出现过
    			}
    			map.put(key, value); // 记录映射
    			values.add(value);// 记录出现过的value,确保唯一。key已经保存在map中了
    		}
    	}
    	return true;
    }

Log in to reply
 

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