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 };

     

  • 相关阅读:
    EA教程 (四) SQLHelper类
    详解包含、扩展和泛化
    几种常用的单例模式详解
    我的分层
    EA教程(二)数据库
    软件版本号如何定义
    精解PV操作之信号量
    eclipse连接数据库驱动汇总
    [Leetcode 17] 13 Roman to Integer
    Short term goal for 2013 rest time
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5170447.html
Copyright © 2011-2022 走看看