zoukankan      html  css  js  c++  java
  • [Leetcode 33] 38 Count and Say

    Problem:

    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.

    Analysis:

    First of all, due to the large number of characters, integer is not enough to represent the result. Use string instead.

    The basic algorithm is simple: maintaining a count for current characters while going through the given string. Every time a new character is accessed, if it's the same as the previous  one, just increase the count by 1; If it's different from the previous one, add the count and the previous character into the result string and then set count to 1, character to current character. Repeat this process until the answer is got.

    The time complexity is O(n), and space complexity is O(n)

    Code:

     1 class Solution {
     2 public:
     3     string countAndSay(int n) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         string res("1");
     7         
     8         while (--n) {
     9             say(res);
    10         }
    11         
    12         return res;
    13     }
    14     
    15     
    16     void say(string &s) {
    17         int cnt = 1, idx = 0;
    18         char val = s[0];
    19         string tmp(s);
    20         s.resize(s.size()*2);
    21         
    22         for (int i=1; i<tmp.size(); i++) {
    23             if (tmp[i] != val) {
    24                 s[idx++] = cnt+'0';
    25                 s[idx++] = val;
    26                 val = tmp[i];
    27                 cnt = 1;
    28             } else {
    29                 cnt++;
    30             }
    31         }
    32         
    33         s[idx++] = cnt + '0';
    34         s[idx++] = val;
    35         s.resize(idx);
    36     }
    37 };
    View Code

    Attention:

    The manipulation of string in C++ is so hard... It took me very much time to finally make the code working.

  • 相关阅读:
    MFC开发编程规范(二)
    Mysql日期和时间函数大全(转)
    php获取客户端IP地址的几种方法
    postgres 查看数据表和索引的大小
    PHP应用memcache函数详解
    css自动截取文字 兼容IE firefox Opera
    JavaScript在IE和Firefox浏览器下的7个差异兼容写法小结
    Zend_Auth与Zend_Acl访问控制链
    去除所有js,html,css代码问题
    [转]那些相见恨晚的 JavaScript 技巧
  • 原文地址:https://www.cnblogs.com/freeneng/p/3096135.html
Copyright © 2011-2022 走看看