Java Iterative Bitwise Solution


  • 0
    K
    public List<String> generateAbbreviations(String word) {
        List<String> result = new ArrayList<String>();
        int n = word.length();
        int size = (1 << n);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            sb.setLength(0);
            int count = 0;
            for (int j = 0; j < n; j++) {
                if ((i & (1<<j)) != 0) {
                    if (count > 0) {
                        sb.append(count);
                        count = 0;
                    }
                    sb.append(word.charAt(j));
                } else {
                    count++;
                }
            }
            if (count > 0)
                sb.append(count);
            result.add(sb.toString());
        }
        return result;
    }

Log in to reply
 

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