• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

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

这道题肯定是DFS/Backtracking, 但是怎么DFS不好想,跟Leetcode: Remove Invalid Parentheses的backtracking很像。

Generalized Abbreviation这道题是当前这个字母要不要abbreviate,要或者不要两种选择,Parentheses那道题是当前括号要不要keep在StringBuffer里,要或不要同样是两种选择。

 Syntax:注意27行使用StringBuffer.setLength(), 因为count一直累加可能变成两位数三位数,delete stringbuffer最后一个字母可能不行,所以干脆设置为最初进recursion的长度

参考了:https://leetcode.com/discuss/76783/easiest-14ms-java-solution-beats-100%25

 1 public class Solution {
 2     public List<String> generateAbbreviations(String word) {
 3         List<String> res = new ArrayList<String>();
 4         dfs(0, word.toCharArray(), new StringBuffer(), 0, res);
 5         return res;
 6     }
 7     
 8     public void dfs(int pos, char[] word, StringBuffer sb, int count, List<String> res) {
 9         int len = word.length;
10         int sbOriginSize = sb.length();
11         if (pos == len) {
12             if (count > 0) {
13                 sb.append(count);
14             }
15             res.add(sb.toString());
16         }
17         else {
18             //choose to abbr word[pos]
19             dfs(pos+1, word, sb, count+1, res);
20             
21             //choose not to abbr word[pos]
22             //first append previous count to sb if count>0
23             if (count > 0) sb.append(count);
24             sb.append(word[pos]);
25             dfs(pos+1, word, sb, 0, res);
26         }
27         sb.setLength(sbOriginSize);
28     }
29 }

 

posted @ 2016-01-01 01:07  neverlandly  阅读(5477)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3