320. Generalized Abbreviation

Description

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"]

Solution

Backtracking, O(n * 2 ^ n), S(n)

Complexity Analysis

Time complexity : O(n * 2^n). For each call to backtrack, it either returns without branching, or it branches into two recursive calls. All these recursive calls form a complete binary recursion tree with 2^n leaves and 2^n - 1 inner nodes. For each leaf node, it needs O(n) time for converting builder to String; for each internal node, it needs only constant time. Thus, the total time complexity is dominated by the leaves. In total that is O(n * 2^n).

Space complexity : O(n). If the return list doesn't count, we only need O(n) auxiliary space to store the characters in StringBuilder and the O(n) space used by system stack. In a recursive program, the space of system stack is linear to the maximum recursion depth which is n in our problem.

题意很好理解,对于word中的每个位置来说,都有缩写和不缩写两种选择,所以总共有2 ^ n中选择。很自然想到利用backtracking来构造所有组合。

class Solution {
    public List<String> generateAbbreviations(String word) {
        List<String> res = new ArrayList<>();
        dfs(word, 0, new StringBuilder(), 0, res);
        return res;
    }
    
    private void dfs(String word, int pos
                     , StringBuilder sb, int count, List<String> res) {
        int originalLen = sb.length();          // keep original sb state
        
        if (pos >= word.length()) {
            sb.append(count > 0 ? count : "");  // don't forget to append count
            res.add(sb.toString());    // cost O(n)!!
        } else {
            // abbreviate
            dfs(word, pos + 1, sb, count + 1, res);
            // don't abbreviate
            sb.append(count > 0 ? count : "");  // append previous abbr chars count  
            sb.append(word.charAt(pos));        // append current char
            dfs(word, pos + 1, sb, 0, res);     // reset count to 0
        }
        
        sb.setLength(originalLen);              // reset sb to original state
    }
}

Bit-manipulation, O(n * 2 ^ n), S(n)

虽然题目里没给定word的长度限制,但我猜测不会很大,因为这道题的时间复杂度一定是指数级的,word太长会TLE。于是可以用bit manipulation去穷举所有选择,这样写也是很清晰的。

class Solution {
    public List<String> generateAbbreviations(String word) {
        List<String> res = new ArrayList<>();
        for (int i = 0; i < (1 << word.length()); ++i) {
            res.add(getAbbr(word, i));
        }
        return res;
    }
    
    private String getAbbr(String word, int bits) {
        StringBuilder sb = new StringBuilder();
        int count = 0;
        
        for (int i = 0; i < word.length(); ++i, bits >>= 1) {
            if ((bits & 1) == 0) {
                sb.append(count > 0 ? count : "")
                    .append(word.charAt(i));
                count = 0;
            } else {
                ++count;
            }
        }
        
        sb.append(count > 0 ? count : "");
        return sb.toString();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,199评论 0 10
  • 一 家的味道 饭馆里飘出的饭香轻撩了一下思绪,感觉回到小学时候,老爹在县城上班不经常回家,每当...
    小高加油阅读 3,462评论 9 12
  • 《1》 满城烟,夜半安,清秋,梦蝶鼾。 《2》 灯影谜,花涧泪,可儿昨夜又美的了谁?命河遥移走,悠幽迷迭香,转谷又...
    是谁动了恻隐之心阅读 2,707评论 0 0
  • 专家老师免费鉴定,快速成交,正规交易平台 征集热线:王总13023213358微信同号 中国钱币多少样 光流通的就...
    王燕儿阅读 3,803评论 0 0

友情链接更多精彩内容