Count and Say (Array Length Encoding) -- LeetCode

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 };

 

 

以上是关于Count and Say (Array Length Encoding) -- LeetCode的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode38. Count and Say

38. Count and Say - Unsolved

leetcode 38 Count and Say

38. Count and Say

38. Count and Say [easy] (Python)

38. Count and Say