1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public boolean wordPattern(String pattern, String str) { Map<String, Character> str2ch = new HashMap<>(); Map<Character, String> ch2str = new HashMap<>(); int n = str.length(); int i = 0; for (char ch : pattern.toCharArray()) { if (i >= n) return false; int j = i; while (j < n && str.charAt(j) != ' ') j++; String tmp = str.substring(i, j); if (str2ch.containsKey(tmp) && str2ch.get(tmp) != ch) return false; if (ch2str.containsKey(ch) && !tmp.equals(ch2str.get(ch))) return false; str2ch.put(tmp, ch); ch2str.put(ch, tmp); i = j + 1; } return i >= n; } }
|