Algorithm/src/main/java/hash/WordPattern.java

40 lines
1.2 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package hash;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* 题目: 290. 单词规律 (wordPattern)
* 描述:给定一种规律 pattern 和一个字符串 s ,判断 s 是否遵循相同的规律。
*
* 这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着双向连接的对应规律。
*
* 示例 1
输入: pattern = "abba", s = "dog cat cat dog"
输出: true
* 链接https://leetcode.cn/problems/word-pattern/
*/
public class WordPattern {
public boolean wordPattern(String pattern, String s) {
String[] res=s.split("\\s");
if(res.length!=pattern.length())
return false;
Map<Character,String> map=new HashMap<>();
Set<String>set=new HashSet<>();
for (int i = 0; i < pattern.length(); i++) {
char cur=pattern.charAt(i);
if(map.containsKey(cur)) {
if(!map.get(cur).equals(res[i])) return false;
}else{
if(set.contains(res[i]))return false;
map.put(cur,res[i]);
set.add(res[i]);
}
}
return true;
}
}