zoukankan      html  css  js  c++  java
  • LeetCode38 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.(Easy)

    分析:

    按照题目要求以此生成新串即可,注意第一个是串是1,即下标从1开始。

    同时,复习使用to_string.

    代码:

     1 class Solution {
     2 public:
     3     string countAndSay(int n) {
     4         string s = "1";
     5         for (int i = 1; i < n; ++i) {
     6             int count = 1;
     7             string temp;
     8             for (int j = 0; j < s.size(); ++j) {
     9                 if (j == s.size() - 1 || s[j] != s[j + 1]) {
    10                     temp += to_string(count);
    11                     temp += s[j];
    12                     count = 1;
    13                 }
    14                 else {
    15                     count ++;
    16                 }
    17             }
    18             s = temp;
    19         }
    20         return s;
    21     }
    22 };
     
  • 相关阅读:
    kvm介绍
    正式班D24
    正式班D23
    正式班D21
    正式班D20
    正式班D19
    正式班D18
    正式班D17
    正式班D16
    正式班D15
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5804682.html
Copyright © 2011-2022 走看看