LeetCode:Count and Say

题目连接html

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

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.code

Given an integer n, generate the nth sequence.htm

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


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

好比第四个字符串是1211,它的读法是 1个一、1个2,2个1,所以第五个字符串是111221。字符串

第五个字符串的读法是:3个一、2个二、1个1,所以第六个字符串是312211                  本文地址get

......string

简单的模拟就能够。io

 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

相关文章
相关标签/搜索