38. Count and Say

本文介绍了一个递归实现的计数与描述算法,通过使用HashMap来跟踪字符及其连续出现次数,该算法能够生成给定整数n对应的计数描述字符串。

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

 1 class Solution {
 2     public String countAndSay(int n) {
 3         String str = "1";
 4         if(n == 1) return str;
 5         return helper(str, n - 1);
 6     
 7         
 8     }
 9     
10     public String helper(String str, int n) {
11         if(n == 0) return str;
12         String res = "";
13         HashMap<Character, Integer> map = new HashMap<>();
14         map.put(str.charAt(0), 1);
15         for(int i = 0; i < str.length(); i++) {
16             if(i != str.length()-1) {
17                 if(str.charAt(i) == str.charAt(i+1)) {
18                     map.put(str.charAt(i+1), map.get(str.charAt(i))+1);
19                 }else {
20                     res = res + map.get(str.charAt(i)) + str.charAt(i);
21                     map.put(str.charAt(i+1), 1);
22                 }
23             }else {
24                 res = res + map.get(str.charAt(i)) + str.charAt(i);
25             }
26         }
27         return helper(res, n - 1);
28     }
29 }

 

转载于:https://www.cnblogs.com/goPanama/p/9618021.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值