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.
题意:
count-and-say序列是如上所示的序列,比如,1,可以读作1个1, 所以下一个数就是11,11可以读作2个1,所以,下一个就是21。给定一个整数n,生成序列的第n个整数序列,该整数序列表示为字符串。
分析:
给定一个整数n,从1开始。不断的获取下一个序列。
采用–n的循环。循环n-1次。
s=getNext(s).
函数:getNext,不断的获取下一个序列。
通过循环迭代器,返回不同于*i的值的下标,就能统计出这个数的个数,然后和i一齐写入到字符流。移动下标,循环i
// LeetCode, Count and Say
// @author 连城 (http://weibo.com/lianchengzju)
//1, 11, 21, 1211, 111221
// 时间复杂度O(n^2),空间复杂度O(n)
class Solution {
public:
string countAndSay(int n) {
string s("1");
while (--n)
s = getNext(s);//获得下一个序列。
return s;
}
string getNext(const string &s) {
stringstream ss;//定义一个字符流。
for (auto i = s.begin(); i != s.end(); )
{
auto j = find_if(i, s.end(), bind1st(not_equal_to<char>(), *i)); //返回一个迭代器。当s=1时,返回end迭代器。
//在i到end范围内找到 操作 i bind1st(const Operation& op, const T& x)就是这么一个操作:x op value,而bind2nd(const Operation& op, const T& x) 这里就是找到不等于i的字符。
ss << distance(i, j) << *i;//将i的值和i,j的距离写入到里面去。
i = j;//i更新成j的距离。
}
return ss.str();//将流转换成字符串。
}
};
新知识点:
stringstream 定义字符流。
.str()将字符流转换成字符串。
bind1st(const Operation& op, const T& x)就是这么一个操作:x op value
bind2st就是 value op x
find_if(i, s.end(), bind1st(not_equal_to(), *i)); 在i和s.end()范围内找到op
distance(i, j) 求i,j的距离。
ss << distance(i, j) << *i; 将数字写入流。