zoukankan      html  css  js  c++  java
  • Count and Say (Array Length Encoding) -- LeetCode

    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.

    思路:模拟过程就行。这里学到的一个东西是stl里有一个int转string的函数叫to_string()。以前一直都是用stringstream来转。。。

     1 class Solution {
     2 public:
     3     string countAndSay(int n) {
     4         if (n < 1) return "";
     5         string res = "1";
     6         for (int i = 2; i <= n; i++)
     7         {
     8             string tem;
     9             char cur = res[0];
    10             int count = 1;
    11             for (int j = 1, n = res.size(); j < n; j++)
    12             {
    13                 if (cur == res[j]) count++;
    14                 else
    15                 {
    16                     tem.append(to_string(count) + cur);
    17                     cur = res[j];
    18                     count = 1;
    19                 }
    20             }
    21             tem.append(to_string(count) + cur);
    22             res = tem;
    23         }
    24         return res;
    25     }
    26 };

    Amazon面试题里有一道array length encoding,和这个题差不多,只不过给的是一个int数组,返回的结果也是一个int数组,且只需要编码一次。

     1 class Solution
     2 {
     3 public:
     4     vector<int> ArrayLengthEncoding(vector<int>& bits)
     5     {
     6         vector<int> res;
     7         if (!bits.size()) return res;
     8         int cur = bits[0], count = 1;
     9         for (int i = 1, n = bits.size(); i < n; i++)
    10         {
    11             if (bits[i] == cur) count++;
    12             else
    13             {
    14                 res.push_back(cur);
    15                 res.push_back(count);
    16                 cur = bits[i];
    17                 count = 1;
    18             }
    19         }
    20         //we need to add the last part of bits
    21         res.push_back(cur);
    22         res.push_back(count);
    23         return res;
    24     }
    25 };

     

  • 相关阅读:
    NodeJs 多核多进程并行框架实作 CNode
    Introduction to XCache ¶
    整理了一些常用的ContentType
    Node 下 Http Streaming 的跨浏览器实现
    libev 设计分析
    master + worker模式的node多核解决框架——nodecluster
    HTTP/1.1: Header Field Definitions
    HTTP/1.1 XCache header field
    XCache and XCacheLookup headers explained
    今天看了一些nodejs的文章,抱欠我又肤欠了。。。
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5170447.html
Copyright © 2011-2022 走看看