leetcode: Count and Say

http://oj.leetcode.com/problems/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.

思路

没啥难度,慢慢数呗,用两个string交叉迭代。

 1 class Solution {
 2 public:
 3     string countAndSay(int n) {
 4         string results[2];
 5         int curr = 0, next = 1;
 6         
 7         results[0] = "1";
 8         for (int i = 1; i < n; ++i) {
 9             int curr_len = results[curr].length();
10             
11             for (int j = 0; j < curr_len; ) {
12                 int sum = 1, k = j + 1;
13                 
14                 while (k < curr_len) {
15                     if (results[curr][j] == results[curr][k]) {
16                         ++k;
17                         ++sum;
18                     }
19                     else {
20                         break;
21                     }
22                 }
23 
24                 results[next].append(1, sum + '0');
25                 results[next].append(1, results[curr][j]);
26                 
27                 j = k;
28             }
29             
30             swap(curr, next);
31             results[next].clear();
32         }
33         
34         return results[curr];
35     }
36 };

 

posted @ 2013-11-04 13:42  移山测试工作室黑灯老师  阅读(368)  评论(0编辑  收藏  举报
count website visits
Buy Computers