原题网址: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"]
方法:深度优先搜索
public class Solution {
private void dfs(char[] wa, int from, int last, String abbr, List<String> result) {
if (from == wa.length) {
result.add(abbr);
return;
}
for(int i=0; i<=wa.length-from; i++) {
dfs(wa, from + Math.max(1, i), i, (i==0? abbr+wa[from] : abbr + i), result);
if (last > 0) break;
}
}
public List<String> generateAbbreviations(String word) {
List<String> result = new ArrayList<>();
dfs(word.toCharArray(), 0, 0, "", result);
return result;
}
}
另一种实现:
public class Solution {
private void find(char[] wa, int len, int[] abbr, int step, List<String> results) {
if (len == wa.length) {
StringBuilder sb = new StringBuilder();
int pos = 0;
for(int i=0; i<step; i++) {
if (abbr[i] == 0) {
sb.append(wa[pos++]);
} else {
sb.append(abbr[i]);
pos += abbr[i];
}
}
results.add(sb.toString());
return;
}
for(int i=0; len+i<=wa.length; i++) {
abbr[step] = i;
find(wa, len+(i==0?1:i), abbr, step+1, results);
if (step>0 && abbr[step-1]>0) break;
}
}
public List<String> generateAbbreviations(String word) {
List<String> results = new ArrayList<>();
find(word.toCharArray(), 0, new int[word.length()], 0, results);
return results;
}
}