Last active
October 15, 2016 05:54
-
-
Save dryear/ddf2fb5740343623b10c190d9a6a0fb2 to your computer and use it in GitHub Desktop.
LeetCode 290. Word Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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