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"]

Solution

public class Solution {
   public List<String> generateAbbreviations(String word) {
        List<String> result = new ArrayList<>();
        helper(word, 0, result, "", false);
        return result;
    }

    private void helper(String word, int index, List<String> result, String sb, boolean isNumPrev) {
        if (word.length() == index) {
            result.add(sb);
            return;
        }

        if (!isNumPrev) {
            for (int i = index + 1; i <= word.length(); i++) {
                helper(word, i, result, sb + String.valueOf(i - index), true);
            }
        }

        helper(word, index + 1, result, sb + word.charAt(index), false);

    }
}

results matching ""

    No results matching ""