Java backtracking AC solution, easy to understand


  • 0
    B
    public List<String> generateAbbreviations(String word) {
        if (word == null || word.length() == 0) {
            List<String> res = new ArrayList<String>();
            res.add("");
            return res;
        }
        return helper(word, 0);
    }
    public List<String> helper(String word, int i) {
        List<String> res = new ArrayList<String>();
        if (i == word.length() - 1) {
            res.add("1");
            res.add(word.substring(i));
            return res;
        }
        List<String> before = helper(word, i + 1);
        for (String s : before) {
            res.add(word.charAt(i) + s);
            int temp = 0, p = 0;
            while (p < s.length() && Character.isDigit(s.charAt(p))) {
                temp = temp * 10 + s.charAt(p) - '0';
                p++;
            }
            res.add(Integer.toString(temp + 1) + s.substring(p));
        }
        return res;
    }

Log in to reply
 

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