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.

Solution:

  1. public class Solution {
  2. public boolean wordPattern(String pattern, String str) {
  3. String[] words = str.split(" ");
  4. if (pattern.length() != words.length) {
  5. return false;
  6. }
  7. Set<String> set = new HashSet<>();
  8. Map<Character, String> map = new HashMap<>();
  9. for (int i = 0; i < words.length; i++) {
  10. String s = words[i];
  11. char p = pattern.charAt(i);
  12. if (map.containsKey(p) && !map.get(p).equals(s)) {
  13. return false;
  14. }
  15. if (!map.containsKey(p) && set.contains(s)) {
  16. return false;
  17. }
  18. map.put(p, s);
  19. set.add(s);
  20. }
  21. return true;
  22. }
  23. }