标签:
原题链接在这里:https://leetcode.com/problems/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"]
题解:
对于当前char有两个选择,第一abbr 当前char, count+1. 第二不abbr当前char, 前append 非零的count再append当前char.
Backtracking 都是setLength回开始的length.
AC Java:
1 public class Solution { 2 public List<String> generateAbbreviations(String word) { 3 List<String> res = new ArrayList<String>(); 4 dfs(word.toCharArray(), new StringBuilder(), res, 0, 0); 5 return res; 6 } 7 8 private void dfs(char [] s, StringBuilder sb, List<String> res, int count, int pos){ 9 int len = sb.length(); 10 if(pos == s.length){ 11 if(count != 0){ 12 sb.append(count); 13 } 14 res.add(sb.toString()); 15 }else{ 16 dfs(s, sb, res, count+1, pos+1); //abbr 当前字母 17 18 //不 abbr 当前字母 19 if(count != 0){ 20 sb.append(count); 21 } 22 dfs(s, sb.append(s[pos]), res, 0, pos+1); 23 } 24 sb.setLength(len); 25 } 26 }
LeetCode Generalized Abbreviation
标签:
原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/5297329.html