码迷,mamicode.com
首页 > 其他好文 > 详细

Count and Say (Array Length Encoding) -- LeetCode

时间:2016-01-30 09:35:35      阅读:317      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/fenshen371/p/5170447.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!