A string such as "word" contains the following abbreviations:

["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"] Given a target string and a set of strings in a dictionary, find an abbreviation of this target string with the smallest possible length such that it does not conflict with abbreviations of the strings in the dictionary.

Each number or letter in the abbreviation is considered length = 1. For example, the abbreviation "a32bc" has length = 4.

Note: In the case of multiple answers as shown in the second example below, you may return any one of them. Assume length of target string = m, and dictionary size = n. You may assume that m ≤ 21, n ≤ 1000, and log2(n) + m ≤ 20. Examples: "apple", ["blade"] -> "a4" (because "5" or "4e" conflicts with "blade")

"apple", ["plain", "amber", "blade"] -> "1p3" (other valid answers include "ap3", "a3e", "2p2", "3le", "3l1").

Solution

public class Solution {

    public String minAbbreviation(String target, String[] dictionary) {
        // represent all words with an integer
        List<Integer> dict = new ArrayList<Integer>();
        int len = target.length();
        for(String s: dictionary) {
            if(target.length() != s.length()) continue;
            int ans = 0;
            for(int i = 0; i < target.length(); i++) {
                if(target.charAt(len - 1 - i) != s.charAt(len - 1- i)) {
                    ans |= (1 << i);
                }
            }
            dict.add(ans);
        }

        if(dict.size() == 0) return ""+len;
        Integer best = null;
        // enumerate all possible cases
        for(int i = 1; i < (1 << len); i++) {
            boolean good = true;
            for(Integer dic: dict) {
                if((i & dic) == 0) {
                    good = false;
                    break;
                }
            }
            if(good && (best == null || getLen(best, len) > getLen(i, len) )) {
                best = i;
            }
        }

        return form(target, best);
    }

    public int getLen(int num, int length) {
        int cnt = 0;
        for(int i = 0; i < length; i++) {
            if( ((num >> i) & 1) == 1) cnt++;
            else if(i == 0 || ((num >> i) & 1) != ( (num >> (i - 1)) & 1) ) cnt++;
        }
        return cnt;
    }

    public String form(String target, int best) {
        StringBuilder sb = new StringBuilder();
        int cnt = 0;
        for(int i = 0; i < target.length(); i++) {
            if( ( (best >> (target.length() - 1 - i)) & 1) == 1 ) {
                // need to output a char
                if(cnt != 0) {
                    sb.append(cnt);
                    cnt = 0;    
                }
                sb.append(target.charAt(i));
            } else {
                cnt++;
            } 
        }
        if(cnt != 0) sb.append(cnt);
        return sb.toString();
    }
}

results matching ""

    No results matching ""