Leetcode - Generalized Abbreviation

My code:

public class Solution {
    public List<String> generateAbbreviations(String word) {
        List<String> ret = new ArrayList<String>();
        if (word == null) {
            return ret;
        }
        
        helper(word, 0, "", 0, ret);
        return ret;
    }
    
    private void helper(String word, int position, String curr, int counter, List<String> ret) {
        if (position >= word.length()) {
            if (counter > 0) {
                curr += counter;
            }
            ret.add(curr);
        }
        else {
            helper(word, position + 1, curr, counter + 1, ret); // abbreviate
            helper(word, position + 1, curr + (counter > 0 ? counter : "") + word.charAt(position), 0, ret); // add character
        }
    }
}

这道题目看答案的。感觉挺怪,google的题目。
backtracking
reference:
https://discuss.leetcode.com/topic/32270/java-backtracking-solution

当指针移动到index处时,我们有两个选择。
要么, abbreviate this character,
要么, 将这个character 插入到current string中

如果打算abbreviate, 那么counter + 1
如果打算插入到当前string中,那就将前面abbreviate 的字符兑现。如果counter > 0,就先插一个数字进去,在跟上当前的字母。

Anyway, Good luck, Richardo! -- 09/02/2016

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,357评论 0 33
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,107评论 19 139
  • LeetCode 刷题随手记 - 第一部分 前 256 题(非会员),仅算法题,的吐槽 https://leetc...
    蕾娜漢默阅读 18,233评论 2 36
  • My code: 这道题木我没有做出来。看了答案才想出来。一开始我写了我的解法,就是看右边的值是否比自己小。小的化...
    Richardo92阅读 4,055评论 0 1
  • My code: reference:https://discuss.leetcode.com/topic/267...
    Richardo92阅读 3,826评论 0 0

友情链接更多精彩内容