Interview 150
Word Pattern
- Problem
- LC 290
- File
- interview150_LC290WordPattern.java
- Path
- pkg5leetcode/interview150/interview150_LC290WordPattern.java
- Package
- pkg5leetcode.interview150
- Command
- java pkg5leetcode/interview150/interview150_LC290WordPattern.java
- Approach
- Bidirectional map pattern char to word and back.
- Complexity
- Time O(n), Space O(n)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.interview150;2 3/*4 * Word Pattern | LC 2905 * APPROACH: Bidirectional map pattern char to word and back.6 * COMPLEXITY: Time O(n), Space O(n)7 */8import java.util.*;9 10public class interview150_LC290WordPattern {11 static boolean wordPattern(String pattern, String s) {12 String[] words = s.split(" ");13 if (pattern.length() != words.length) return false;14 Map<Character, String> ps = new HashMap<>();15 Map<String, Character> sp = new HashMap<>();16 for (int i = 0; i < pattern.length(); i++) {17 char c = pattern.charAt(i);18 String w = words[i];19 if (ps.containsKey(c) && !ps.get(c).equals(w)) return false;20 if (sp.containsKey(w) && sp.get(w) != c) return false;21 ps.put(c, w);22 sp.put(w, c);23 }24 return true;25 }26 27 public static void main(String[] args) {28 check(wordPattern("abba", "dog cat cat dog"), "case1");29 check(!wordPattern("abba", "dog cat cat fish"), "case2");30 System.out.println("all tests passed");31 }32 33 static void check(boolean cond, String name) {34 if (!cond) throw new AssertionError("FAILED: " + name);35 System.out.println(" PASS " + name);36 }37}