LeetCodeOJ: 38. Count and Say

来源:互联网 发布:网游数据库 编辑:程序博客网 时间:2024/05/20 10:12

Total Accepted: 75530 Total Submissions: 265272 Difficulty: Easy

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.

class Solution {public:    string countAndSay(int n) {                string str1 = "1";        n--;        while(n--){            string str2 = "";            for(int i = 0; i < str1.length();){                int cur_count = 0;                char cur_n = str1[i];                while(cur_n == str1[i] && i < str1.length()){                    cur_count++;                    i++;                }                str2 += (cur_count+'0');                str2 += cur_n;            }                        str1 = str2;        }                return str1;    }};





0 0