码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Generalized Abbreviation

时间:2016-03-20 11:42:52      阅读:771      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里: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"]

题解:

对于当前char有两个选择,第一abbr 当前char, count+1. 第二不abbr当前char, 前append 非零的count再append当前char.

Backtracking 都是setLength回开始的length.

AC Java:

 1 public class Solution {
 2     public List<String> generateAbbreviations(String word) {
 3         List<String> res = new ArrayList<String>();
 4         dfs(word.toCharArray(), new StringBuilder(), res, 0, 0);
 5         return res;
 6     }
 7     
 8     private void dfs(char [] s, StringBuilder sb, List<String> res, int count, int pos){
 9         int len = sb.length();
10         if(pos == s.length){
11             if(count != 0){
12                 sb.append(count);
13             }
14             res.add(sb.toString());
15         }else{
16             dfs(s, sb, res, count+1, pos+1); //abbr 当前字母
17             
18             //不 abbr 当前字母
19             if(count != 0){         
20                 sb.append(count);
21             }
22             dfs(s, sb.append(s[pos]), res, 0, pos+1);
23         }
24         sb.setLength(len);
25     }
26 }

 

LeetCode Generalized Abbreviation

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/5297329.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!