【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) {
Map<Character, String> map = new HashMap<>();
Set<String> set = new HashSet<>();
int index = 0;
for (int i = 0; i < pattern.length(); i++) {
char ch = pattern.charAt(i);
int start = index;
if (index >= s.length()) return false;
while (index < s.length() && s.charAt(index) != ' ') {
index++;
}
String cur = s.substring(start, index);
index++;
String pre = map.get(ch);
if (pre == null) {
if (set.contains(cur)) return false;
set.add(cur);
map.put(ch, cur);
} else {
if (!pre.equals(cur)) return false;
}
}
return index >= s.length();
}
}
执行耗时:1 ms,击败了98.94% 的Java用户
内存消耗:36.4 MB,击败了80.89% 的Java用户
![](https://i-blog.csdnimg.cn/blog_migrate/6c56d31f951aece27c5faae608dfac2e.jpeg)