高级农民
- 积分
- 2288
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2015-8-24
- 最后登录
- 1970-1-1
|
top down版:- import java.util.*;
- public class CountAndSay2 {
- public static List<String> solution(String input) {
- Map<Integer, List<String>> memo = new HashMap<>();
- return helperWithMeomory(memo, input, 0);
- }
- private static List<String> helperWithMeomory(Map<Integer, List<String>> memo, String input, int start) {
- if (memo.containsKey(start)) {
- return memo.get(start);
- }
- if (start == input.length()) {
- return Arrays.asList("");
- }
- List<String> res = new LinkedList<>();
- if (input.charAt(start) == '0') {
- memo.put(start, res);
- return res;
- }
- for (int i = start; i < input.length() - 1; i++) {
- int count = Integer.parseInt(input.substring(start, i + 1));
- int num = input.charAt(i + 1) - '0';
- StringBuilder sb = new StringBuilder();
- for (int j = 0; j < count; j++) {
- sb.append(num);
- }
- String strToAdd = sb.toString();
- List<String> tempList = helperWithMeomory(memo, input, i + 2);
- for (String tempStr : tempList) {
- res.add(strToAdd + tempStr);
- }
- }
- memo.put(start, res);
- return res;
- }
- public static void main(String[] args) {
- System.out.println(solution("1112"));
- }
- }
复制代码 |
|