LeetCode 320. Generalized Abbreviation(产生缩写)

该博客探讨如何利用深度优先搜索算法解决LeetCode上的320题——词的全称问题。通过实例展示了如何生成一个单词的所有可能缩写形式。
摘要由CSDN通过智能技术生成

原题网址: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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值