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
pattern
andstr
contains only lowercase alphabetical letters. - Both
pattern
andstr
do not have leading or trailing spaces. - Each word in
str
is separated by a single space. - Each letter in
pattern
must 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;
}
}