My simplified java version


  • 2
    S

    My simplified java version

    public class Solution {
    public boolean wordPatternMatch(String pattern, String str) {
        Map<Character, String> map = new HashMap<>();
    
        return helper(pattern, 0, str, 0, map);
    }
    
    public boolean helper(String pattern, int pPos, String str, int sPos, Map<Character, String> map) {
        if(sPos == str.length() && pPos == pattern.length()) return true;
        
        if(sPos == str.length() || pPos == pattern.length()) return false;
     
        char c = pattern.charAt(pPos);
        
        for(int i = sPos; i < str.length(); i++) {
            String substr = str.substring(sPos, i+1);
            
            if(map.containsKey(c) && map.get(c).equals(substr) ) {
                if(helper(pattern, pPos+1, str, i+1, map)) return true;
            }
            
            if(!map.containsKey(c) && !map.containsValue(substr) ) {
                map.put(c, substr);
                if(helper(pattern, pPos+1, str, i+1, map)) return true;
                map.remove(c);
            }
        }           
        return false;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.