题目:
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
.
Example 1:
Input: pattern = "abba"
, str = "dog cat cat dog"
Output: true
Example 2:
Input:pattern = "abba"
, str = "dog cat cat fish"
Output: false
Example 3:
Input: pattern = "aaaa"
, str = "dog cat cat dog"
Output: false
Example 4:
Input: pattern = "abba"
, str = "dog dog dog dog"
Output: false
public class WordPattern {
public boolean wordPattern(String pattern, String str) {
if (str == null || str.length() == 0) {
return false;
}
Map<Integer, String> keyMap = new HashMap<>();
String[] target = str.split(" ");
if (pattern.length() != target.length) {
return false;
}
for (int i = 0; i < pattern.length(); i++) {
int patternKey = pattern.charAt(i);
if (keyMap.containsKey(patternKey)) {
if (!keyMap.get(patternKey).equals(target[i]))
return false;
} else {
//key not exits but value has exits .
//this need return false
if (keyMap.containsValue(target[i])) return false;
keyMap.put(patternKey, target[i]);
}
}
return true;
}
public static void main(String[] args) {
String pattern = "abab";
String str = "fish pig fish pig";
System.out.println(new WordPattern().wordPattern(pattern, str));
}
}
public class WordPattern {
public boolean wordPattern(String pattern, String str) {
if (str == null || str.length() == 0) {
return false;
}
String[] array = new String[26];
Set<String> set = new HashSet();
int fast = 0;
int slow = 0;
int p = 0;
while (fast < str.length() && p < pattern.length()) {
if (str.charAt(fast) == ' ' || fast == str.length() - 1) {
String temp = "";
if (fast == str.length() - 1) {
temp = str.substring(slow, fast + 1);
}else{
temp = str.substring(slow, fast);
}
if (array[pattern.charAt(p) - 'a'] != null) {
if (!array[pattern.charAt(p) - 'a'].equals(temp)) {
return false;
}
}else{
if (set.add(temp)) {
array[pattern.charAt(p) - 'a'] = temp;
}else{
return false;
}
}
slow = fast + 1;
p ++;
}
fast ++;
}
if (fast < str.length() || p < pattern.length()) {
return false;
}
return true;
}
public static void main(String[] args) {
String pattern = "abab";
String str = "fish pig fish pig";
System.out.println(new WordPattern().wordPattern(pattern, str));
}
}