Description:
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.
Solution:
From tuition, we can use a hashmap to deal with this problem.
Just need to pay attention to some tricks.
1. the length of keys and values should be the same
2. <key, value> should be a one-to-one pair
<span style="font-size:18px;">import java.util.HashMap;
import java.util.Hashtable;
import java.util.Scanner;
public class Solution {
public boolean wordPattern(String pattern, String str) {
HashMap<Character, String> map = new HashMap<Character, String>();
Scanner scan = new Scanner(str);
int count = 0;
char key;
String value;
while (scan.hasNext()) {
if (count == pattern.length())
return false;
value = scan.next();
key = pattern.charAt(count);
if (map.containsKey(key)) {
System.out.println(key + " " + value);
if (!value.equals(map.get(key)))
return false;
} else if (map.containsValue(value)) {
return false;
} else
map.put(key, value);
count++;
}
if (pattern.length() != count)
return false;
return true;
}
}</span>