LeetCode 291: Word Pattern II

Problem Description

Explanation:

Given a pattern and a string s, we need to determine if s follows the same pattern as the given pattern.

To solve this problem, we can use backtracking. We will maintain a mapping between characters in the pattern and substrings in the input string. We will try all possible mappings and backtrack if we encounter a mismatch.

Algorithm:

  1. Create a hashmap to store the mapping between characters in the pattern and substrings in the input string.
  2. Define a recursive backtracking function that takes the index of the current character in the pattern and the starting index in the input string as parameters.
  3. If we reach the end of the pattern and the input string, return true.
  4. If we reach the end of either the pattern or the input string, return false.
  5. For the current character in the pattern, try all possible substrings from the current index in the input string.
  6. If the mapping between the character and substring is valid, recursively check the remaining characters in the pattern and input string.
  7. If at any point we encounter a mismatch, backtrack and try a different mapping.

Time Complexity: O(N^M) where N is the length of the input string and M is the length of the pattern. Space Complexity: O(M) where M is the length of the pattern.

: :

Solutions

import java.util.HashMap;

class Solution {
    public boolean wordPatternMatch(String pattern, String s) {
        HashMap<Character, String> map = new HashMap<>();
        return backtrack(pattern, s, 0, 0, map);
    }
    
    private boolean backtrack(String pattern, String s, int pIdx, int sIdx, HashMap<Character, String> map) {
        if (pIdx == pattern.length() && sIdx == s.length()) {
            return true;
        }
        if (pIdx == pattern.length() || sIdx == s.length()) {
            return false;
        }
        
        char c = pattern.charAt(pIdx);
        
        if (map.containsKey(c)) {
            String mapped = map.get(c);
            if (s.startsWith(mapped, sIdx)) {
                return backtrack(pattern, s, pIdx + 1, sIdx + mapped.length(), map);
            } else {
                return false;
            }
        }
        
        for (int i = sIdx; i < s.length(); i++) {
            String word = s.substring(sIdx, i + 1);
            if (map.containsValue(word)) {
                continue;
            }
            map.put(c, word);
            if (backtrack(pattern, s, pIdx + 1, i + 1, map)) {
                return true;
            }
            map.remove(c);
        }
        
        return false;
    }
}

Loading editor...