本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

LeetCode:Count and Say

题目链接

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.

Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.


题目描述的不是很清楚,其实就是第i+1个字符串是第i个字符串的读法,第一字符串为 “1”

比如第四个字符串是1211,它的读法是 1个1、1个2,2个1,因此第五个字符串是111221。

第五个字符串的读法是:3个1、2个2、1个1,因此第六个字符串是312211                  本文地址

......

简单的模拟就可以。

复制代码
 1 class Solution {
 2 public:
 3     string countAndSay(int n) {
 4         if(n < 1)return "";
 5         string prev = "1";
 6         for(int i = 2; i <= n; i++)
 7         {
 8             char curChar = prev[0];
 9             int times = 1;//curChar 出现的次数
10             string tmpstr;
11             prev.push_back('#');//处理边界条件
12             for(int k = 1; k < prev.size(); k++)
13             {
14                 if(prev[k] == curChar)
15                     times++;
16                 else
17                 {
18                     tmpstr += to_string(times);
19                     tmpstr.push_back(curChar);
20                     curChar = prev[k];
21                     times = 1;
22                 }
23             }
24             prev = tmpstr;
25         }
26         return prev;
27     }
28 };
复制代码

其实我们可以发现字符串中永远只会出现1,2,3这三个字符,假设第k个字符串中出现了4,那么第k-1个字符串必定有四个相同的字符连续出现,假设这个字符为1,则第k-1个字符串为x1111y。第k-1个字符串是第k-2个字符串的读法,即第k-2个字符串可以读为“x个1,1个1,1个y” 或者“*个x,1个1,1个1,y个*”,这两种读法分别可以合并成“x+1个1,1个y” 和 “*个x,2个1,y个*”,代表的字符串分别是“(x+1)11y” 和 "x21y",即k-1个字符串为“(x+1)11y” 或 "x21y",不可能为“x1111y”.

 

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3776356.html

 

 

 

posted @   tenos  阅读(7396)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架

本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

公益页面-寻找遗失儿童

点击右上角即可分享
微信分享提示