【LeetCode】290. Word Pattern

问题链接:https://leetcode.com/problems/word-pattern/

思路:

使用一个map存储映射关系即可

public boolean wordPattern(String pattern, String str) {
		String first = pattern;
		String[] second = str.split(" ");
		if(first.length()!=second.length) {
			return false;
		}
		Map<Character, String> m = new HashMap<>();
		for(int i=0;i<first.length();i++) {
			if(m.containsKey(first.charAt(i))||m.containsValue(second[i])) {
				if(!m.containsKey(first.charAt(i))||!m.get(first.charAt(i)).equals(second[i])){
					return false;
				};
			} else {
				m.put(first.charAt(i), second[i]);
			}
		}
		return true;
    }