Skip to content

Instantly share code, notes, and snippets.

@dryear
Last active October 15, 2016 05:54
Show Gist options
  • Save dryear/ddf2fb5740343623b10c190d9a6a0fb2 to your computer and use it in GitHub Desktop.
Save dryear/ddf2fb5740343623b10c190d9a6a0fb2 to your computer and use it in GitHub Desktop.
LeetCode 290. Word Pattern
/**
* https://leetcode.com/problems/word-pattern/
*
* O(n) runtime, O(n) space
*
* simply verify it is a bijection by using HashSet and HashMap
* use HashMap to verify that if a = b, then f(a) = f(b)
* use HashSet to verify that if f(a) = f(b), then a = b
*/
public class Solution {
public boolean wordPattern(String pattern, String str) {
String[] strs = str.split(" "); // note str.split(" ") here
if (pattern.length() != strs.length) {
return false;
}
HashSet<String> set = new HashSet<>();
HashMap<Character, String> map = new HashMap<>();
for (int i = 0; i < pattern.length(); i++) {
char key = pattern.charAt(i);
String value = strs[i];
if (map.containsKey(key)) {
if (!map.get(key).equals(value)) {
return false;
}
} else if (set.contains(value)) {
return false;
} else {
set.add(value);
map.put(key, value);
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment