320. Generalized Abbreviation
LeetCode 320. Generalized Abbreviation
Description
A word's generalized abbreviation can be constructed by taking any number of non-overlapping substrings and replacing them with their respective lengths. For example, "abcde"
can be abbreviated into "a3e"
("bcd"
turned into "3"
), "1bcd1"
("a"
and "e"
both turned into "1"
), and "23"
("ab"
turned into "2"
and "cde"
turned into "3"
).
Given a string word
, return a list of all the possible generalized abbreviations of word
. Return the answer in any order.
Example 1:
Example 2:
Constraints:
1 <= word.length <= 15
word
consists of only lowercase English letters.
Tags
Bit Manipulation
Solution
We can observe that the result is sort of related to bits representation (since the length of output is 2^n, n = len(word)
). Thus, we iterate a bit-mask variable from 0
to 2^n-1
. (e.g. for word = "word"
, we iterate from 0000
to 1111
), and rules to generate a word are:
we initialize a counter variable to count continuous
1
, as well as a byte slicew
whose capacity isn
;we check bits of the current bit-mask one by one with the pointer
j
:if the bit
bitmask[j]
is1
, increase the counter by 1;if the bit
bitmask[j]
is0
, convert the counter type from integer to string only if the counter is greater than 0, and concatenatew
to it, then clear the counter. Also, appendword[j]
tow
.
convert the counter type from integer to string only if the counter is greater than 0, and concatenate
w
to it.convert the type of
w
from[]byte
tostring
, and append it to the result slice.
Complexity
Time complexity:
Space complexity:
Code
Last updated
Was this helpful?