zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    第七周作业
    第六周作业
    CSS
    12 week work
    7 week work
    6 week work 3
    6 week work 2
    6 week work 1
    常用的网络服务小总结
    网络基础设置
  • 原文地址:https://www.cnblogs.com/panda_lin/p/count_and_say.html
Copyright © 2011-2022 走看看