题目链接:https://leetcode.com/problems/word-pattern/
题目:
Given a pattern
and a string str
,
find if str
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 str
.
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:
You may assume pattern
contains only lowercase letters, and str
contains
lowercase letters separated by a single space.
思路:
1、pattern字符相等的位置对应的字符串中的单词应该是相等的,pattern字符不相等的位置对应的字符串中单词应该也是不相等的。时间复杂度为
O(n^2),空间复杂度为O(1)。
2、用HashMap存储字符到单词的映射关系,时间复杂度为O(n),空间复杂度为O(n)。
算法1:
-
public boolean wordPattern(String pattern, String str) {
-
String strs[] = str.split(" ");
-
char patterns[] = pattern.toCharArray();
-
-
if (strs.length != patterns.length || strs.length == 0) {
-
return false;
-
}
-
-
for (int i = 0; i < patterns.length; i++) {
-
for (int j = i + 1; j < patterns.length; j++) {
-
if (patterns[i] == patterns[j]) {
-
if (!strs[i].equals(strs[j])) {
-
return false;
-
}
-
} else {
-
if (strs[i].equals(strs[j])) {
-
return false;
-
}
-
}
-
}
-
}
-
return true;
-
}
算法2:
-
public boolean wordPattern(String pattern, String str) {
-
String strs[] = str.split(" ");
-
char patterns[] = pattern.toCharArray();
-
HashMap<Character,String> map = new HashMap<Character,String>();
-
HashMap<String,Character> map2 = new HashMap<String,Character>();
-
if (strs.length != patterns.length || strs.length == 0) {
-
return false;
-
}
-
for (int i = 0; i < patterns.length; i++) {
-
if(!map.containsKey(patterns[i])){
-
map.put(patterns[i], strs[i]);
-
}else{
-
if(!map.get(patterns[i]).equals(strs[i])){
-
return false;
-
}
-
}
-
-
if(!map2.containsKey(strs[i])){
-
map2.put(strs[i], patterns[i]);
-
}else{
-
if(!map2.get(strs[i]).equals(patterns[i])){
-
return false;
-
}
-
}
-
}
-
return true;
-
}
【Leetcode】Word Pattern
原文:http://blog.csdn.net/yeqiuzs/article/details/51622679