38. Count and Say序列 Count and Say

Posted Long Long Journey

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了38. Count and Say序列 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.

求出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的主要内容,如果未能解决你的问题,请参考以下文章

算法LeetCode算法题-Count And Say

LeetCode38. Count and Say

38. Count and Say - Unsolved

leetcode 38 Count and Say

38. Count and Say

38. Count and Say