320. Generalized Abbreviation

Write a function to generate the generalized abbreviations of a word.
Example:
Given word = "word", return the following list (order does not matter):

["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]

一刷
题解:abbreviation, backtracking

class Solution {
    public List<String> generateAbbreviations(String word) {
        List<String> res = new ArrayList<>();
        bt(res, word, 0, "", 0);
        return res;
    }
    
    private void bt(List<String> res, String word, int pos, String cur, int count){
        if(pos == word.length()){
            if(count>0) cur+=count;
            res.add(cur);
        }
        else{
            bt(res, word, pos+1, cur, count+1);//abrevation the pos
            if(count>0){
                bt(res, word, pos+1, cur+count+word.charAt(pos), 0);
            }else{
                bt(res, word, pos+1, "" + word.charAt(pos), 0);
            }
        }
    }
}

二刷
类似于DFS, 分清abbreviation和not abbreviation的情况

class Solution {
    public List<String> generateAbbreviations(String word) {
        List<String> res = new ArrayList<>();
        //if(word == null || word.length()==0) return res;
        bt(word, 0, res, 0, "");
        return res;
    }
    
    private void bt(String word, int pos, List<String> res, int count, String cur){
        //abbreviation or not
        if(pos == word.length()){
            if(count>0) res.add(cur + count);
            else res.add(cur);
            return;
        }
        //abbreviation
        bt(word, pos+1, res, count+1, cur);
        
        //not abbreviation
        if(count != 0) bt(word, pos+1, res, 0, cur+count+word.charAt(pos));
        else bt(word, pos+1, res, 0, cur+word.charAt(pos));
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 银河系中的每一颗星都有自己的角落, 它们在那里默默的观望着我们。 试问,我们的心宿在哪一颗星上? 又应在此刻存放于...
    梁熹光阅读 217评论 0 0
  • 在工作单位里,我自问是称职的办公室主任。 在小区里,我也是业主代表,受大家欢迎。 在家里,我也算是一个好爸爸,好丈...
    天亦阅读 617评论 4 3
  • 不知道为什么打开了这本书,结果越看越被吸引,这真是一种奇妙的感觉!文字之所以动人,都源于它来自于真实的生活...
    CD_e1c6阅读 1,336评论 0 2