The original title link is here: https://leetcode.com/problems/generalized-abbreviation/
Topic:
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"]
Exercises
For the current char there are two choices, the first abbr the current char, and the count+1. The second does not abbr the current char, before the count of nonzero append append the current char.
Backtracking is the length of the SetLength back to the beginning.
AC Java:
1 Public classSolution {2 PublicList<string>generateabbreviations (String word) {3list<string> res =NewArraylist<string>();4DFS (Word.tochararray (),NewStringBuilder (), res, 0, 0);5 returnRes;6 }7 8 Private voidDfsChar[] s, StringBuilder SB, list<string> Res,intCountintPOS) {9 intLen =sb.length ();Ten if(pos = =s.length) { One if(Count! = 0){ A Sb.append (count); - } - Res.add (sb.tostring ()); the}Else{ -DFS (S, SB, res, count+1, pos+1);//abbr Current Letter - - //do not abbr the current letter + if(Count! = 0){ - Sb.append (count); + } ADFS (S, sb.append (S[pos)), res, 0, pos+1); at } - sb.setlength (len); - } -}
Leetcode generalized abbreviation