首页 > 代码库 > 38. Count and Say序列 Count and Say

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




null


38. Count and Say序列 Count and Say