Leetcode 320 Generalized Abbreviation

320 Generalized Abbreviation


Write a function to generate the generalized abbreviations of a word.
Note: The order of the output does not matter.

Example:
Input: “word”
Output:
[“word”, “1ord”, “w1rd”, “wo1d”, “wor1”, “2rd”, “w2d”, “wo2”, “1o1d”, “1or1”, “w1r1”, “1o2”, “2r1”, “3d”, “w3”, “4”]

典型Backtrack+剪枝

//剪枝:已经map到某char上的string不能再拿来match

    public boolean wordPatternMatch(String pattern, String str) {
        return matchHelper(pattern, str, new HashMap<>(), 0, 0, new HashSet<>());
    }

    private boolean matchHelper(String pattern, String str, 
                                Map<Character, String> map, 
                                int indexP, int indexS,
                                Set<String> usedStrSet) {
        if (indexP >= pattern.length() || indexS >= str.length()) {
            return (indexP == pattern.length() && indexS == str.length());
        }
        char c = pattern.charAt(indexP);
        if (map.containsKey(c)) {
            if (indexS + map.get(c).length() > str.length() 
                || !map.get(c).equals(str.substring(indexS, indexS + map.get(c).length()))) 
                return false;
            return matchHelper(pattern, str, map, indexP + 1, indexS + map.get(c).length(), usedStrSet);
        } else {
        	//backtrack
            for (int i = indexS; i < str.length() && 
                 i + pattern.length() - 1 - indexP < str.length(); i++) {
                //string already mapped to a char, can't map to other 
                if (usedStrSet.contains(str.substring(indexS, i + 1)))
                    continue;
                map.put(c, str.substring(indexS, i + 1));
                usedStrSet.add(str.substring(indexS, i + 1));
                if (matchHelper(pattern, str, map, indexP + 1, i + 1, usedStrSet)) 
                	return true;
                map.remove(c);
                usedStrSet.remove(str.substring(indexS, i + 1));
            }
        }
        return false;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值