【LeetCode】290. Word Pattern 单词规律(Easy)(JAVA)
题目地址: https://leetcode.com/problems/word-pattern/
题目描述:
Given a pattern and a string s, find if s follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.
Example 1:
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Example 2:
Input: pattern = "abba", s = "dog cat cat fish"
Output: false
Example 3:
Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false
Example 4:
Input: pattern = "abba", s = "dog dog dog dog"
Output: false
Constraints:
- 1 <= pattern.length <= 300
- pattern contains only lower-case English letters.
- 1 <= s.length <= 3000
- s contains only lower-case English letters and spaces ’ '.
- s does not contain any leading or trailing spaces.
- All the words in s are separated by a single space.
题目大意
给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。
这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律
说明:
你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。
解题方法
- 要字符和字符串一一对应,不能是多对一也不能是一对多
- 把对应关系记录下来,然后每次查看是否相同即可
- note: 要考虑长度不一的问题
class Solution {
public boolean wordPattern(String pattern, String s) {
int pIndex = 0;
int sIndex = 0;
Map<Character, String> map = new HashMap<>();
Set<String> set = new HashSet<>();
while (sIndex < s.length() && pIndex < pattern.length()) {
Character ch = pattern.charAt(pIndex);
pIndex++;
int start = sIndex;
while (sIndex < s.length() && s.charAt(sIndex) != ' ') {
sIndex++;
}
String cur = s.substring(start, sIndex);
sIndex++;
String pre = map.get(ch);
if (pre == null) {
if (set.contains(cur)) return false;
} else {
if (!pre.equals(cur)) return false;
}
map.put(ch, cur);
set.add(cur);
}
return sIndex >= s.length() && pIndex >= pattern.length();
}
}
执行耗时:1 ms,击败了98.95% 的Java用户
内存消耗:36.8 MB,击败了26.90% 的Java用户
![](https://img-blog.csdnimg.cn/20201107174624800.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzE2OTI3ODUz,size_16,color_FFFFFF,t_70#pic_center)