Word Pattern
Total Accepted: 1733
Total Submissions: 6204
Difficulty: Easy
Given a pattern and a string str, find if str follows the same pattern.
Examples:
- pattern =
"abba", str ="dog cat cat dog"should return true. - pattern =
"abba", str ="dog cat cat fish"should return false. - pattern =
"aaaa", str ="dog cat cat dog"should return false. - pattern =
"abba", str ="dog dog dog dog"should return false.
Notes:
- Both
patternandstrcontains only lowercase alphabetical letters. - Both
patternandstrdo not have leading or trailing spaces. - Each word in
stris separated by a single space. - Each letter in
patternmust map to a word with length that is at least 1.
Credits:
Special thanks to @minglotus6 for adding this problem and creating all test cases.
char 和 string 一一对应. 建一个map. 同时set里面保存string, 避免重复, 出现多对1的情况.
[CODE]
public class Solution {
public boolean wordPattern(String pattern, String str) {
//input check
String[] strs = str.split(" ");
if(pattern.length() != strs.length ) return false;
Map<Character, String> map = new HashMap<>();
Set<String> unique = new HashSet<>();
for(int i=0; i<pattern.length(); i++) {
char c = pattern.charAt(i);
if(map.containsKey(c) ) {
if(!map.get(c).equals(strs[i])) return false;
} else {
if(unique.contains(strs[i])) return false;
map.put(c, strs[i]);
unique.add(strs[i]);
}
}
return true;
}
}
本文介绍了一种用于判断字符串是否遵循给定模式的算法。通过使用HashMap来建立字符与单词之间的映射关系,并利用HashSet确保每个字符映射到不同的单词,以此实现模式与字符串的有效匹配。
1万+

被折叠的 条评论
为什么被折叠?



