java 320.广义缩写(第1个).java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 320.广义缩写(第1个).java相关的知识,希望对你有一定的参考价值。

public class Solution {
    private void helper(String word, int start, int len, String temp, List<String> res) {
        if (start == word.length()) {
            if (len > 0) temp += len;
            res.add(temp);
            return;
        }
        helper(word, start + 1, len + 1, temp, res);
        helper(word, start + 1, 0, temp + (len > 0 ? len : "") + word.charAt(start), res);
    }
    public List<String> generateAbbreviations(String word) {
        List<String> res = new ArrayList<>();
        helper(word, 0, 0, "", res);
        return res;
    }
}
public class Solution {
    public List<String> generateAbbreviations(String word) {
        List<String> res = new ArrayList<>();
        if (word == null) {
            return res;
        }
        char[] chs = word.toCharArray();
        backtrack(res, new StringBuilder(), chs, 0, 0);
        return res;
    }
    
    private void backtrack(List<String> res, StringBuilder temp, char[] chs, int start, int count) { // count means number of chars to be abbreviated
        if (start == chs.length) {
            if (count > 0) {
                temp.append(count);
            }
            res.add(temp.toString());
        } else {
            int oldLen = temp.length();
            backtrack(res, temp, chs, start + 1, count + 1);
            temp.setLength(oldLen);
            
            if (count > 0) {
                temp.append(count);
            }
            backtrack(res, temp.append(chs[start]), chs, start + 1, 0);
            temp.setLength(oldLen);
        }
    }
}
public class Solution {
    public List<String> generateAbbreviations(String word) {
        List<String> l = new ArrayList<String>();
        dfs(l,word,"",0,0);
        return l;
    }
    public void dfs(List<String> l, String word, String s, int num, int pos){
        if(pos == word.length()){
            if(num > 0){
                s = s + num;
            }
            l.add(s);
            return;
        }
        char ch = word.charAt(pos);
        dfs(l,word,num > 0 ? s+num+ch:s+ch,0,pos+1);
        dfs(l,word,s,num+1,pos+1);
    }
}

以上是关于java 320.广义缩写(第1个).java的主要内容,如果未能解决你的问题,请参考以下文章

java 320.广义缩写(第1个).java

java 320.广义缩写(第1个).java

java 320.广义缩写(第1个).java

java 320.广义缩写(第1个).java

java 408.有效词的缩写(第1个).java

java 408.有效词的缩写(第1个).java