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

38. Count and Say序列 Count and Say

时间:2017-04-08 23:44:36      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:begin   uri   lan   class   length   generate   uil   size   ...   

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.

求出Count and Say序列的第N项

  1. public class Solution {
  2. public string CountAndSay(int n) {
  3. string str = "1";
  4. for (int i = 0; i < n-1; i++) {
  5. str = GetNewString(str);
  6. }
  7. return str;
  8. }
  9. public string GetNewString(string str) {
  10. StringBuilder newStr = new StringBuilder();
  11. int count = 1;
  12. for (int i = 1; i < str.Length; i++) {
  13. if (str[i] != str[i - 1]) {
  14. newStr.Append(count.ToString() + str[i - 1].ToString());
  15. count = 1;
  16. } else {
  17. count++;
  18. }
  19. }
  20. newStr.Append(count.ToString() + str[str.Length - 1]);
  21. return newStr.ToString();
  22. }
  23. }






38. Count and Say序列 Count and Say

标签:begin   uri   lan   class   length   generate   uil   size   ...   

原文地址:http://www.cnblogs.com/xiejunzhao/p/cc5d7c1094f7838bb67b410ca2971729.html

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