LeetCode 527 Word Abbreviation

本文介绍了一种用于生成字符串缩写的算法。该算法采用递归去重的方法,通过维护前缀长度数组来避免重复计算,最终生成一个列表,其中每个字符串都被适当地缩写。文章包含完整的Java代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Note:

This is kind of recurrsive dedup questions.

class Solution {
    public List<String> wordsAbbreviation(List<String> dict) {
        List<String> result = new ArrayList<>();
        int[] prefix = new int[dict.size()];
        String[] current = new String[dict.size()];
        for (int i = 0; i < current.length; i++) {
            prefix[i] = 1;
            current[i] = addAbb(dict.get(i), 1);
        }
        
        for (int i = 0; i < current.length; i++) {
            while (true) {
                Set<Integer> dups = new HashSet<>();
                for (int j = i + 1; j < current.length; j++) {
                    if (current[j].equals(current[i])) {
                        dups.add(j);
                    }
                }
                if (dups.size() == 0) break;
                dups.add(i);
                
                for (int dup : dups) {
                    current[dup] = addAbb(dict.get(dup), ++prefix[dup]);
                }
            }
            result.add(current[i]);
        }
        return result;
    }
    
    private String addAbb(String s, int len) {
        if (len >= s.length() - 2) return s;
        StringBuilder result = new StringBuilder();
        result.append(s.substring(0, len)).append(s.length() - len  - 1).append(s.charAt(s.length() - 1));
        return result.toString();
    }
}

 

转载于:https://www.cnblogs.com/shuashuashua/p/7646245.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值