题目链接:Leetcode 38
描述一下题目:
说起来都是泪啊... 2018年3月18号那场PAT乙级考试的第四题就是这个... 没做出来,所以啊,Leetcode要多刷刷。。
给定一个如下规律的数列,求出第n项。
1,11,21,1211,111221....
解题思路:
递归,递归,递归! 重要的话说三遍!
分析这个数组的规律,第一项是1,第二项是11,代表1(count)个1(element),然后第三项是描述第二项,有2(count)个1(element),第四项描述第三项,有1(count)个2(element)和1(count)个1(element),到这里可能就觉得这个多简单啊,每个元素搞个计数器,遇到就++,最后输出,等我们看到第五项的时候就发现不是这样的,并没有出现3(count)个1(element),在2之后做了分割,也就是就算是相同的元素,中间被不一样的元素隔开以后就要重新计数。所以第五项描述为1(count)个1(element),1(count)个2(element),2(count)个1(element)。
代码如下:(C++)
/******************************************************************************* Copyright © 2018-20xx Qiao Chuncheng, All Rights Reserved. File name: 038[报数].cpp Author: Qiao Chuncheng Version: v1.0 Date: 2018-04-17 *******************************************************************************/ class Solution { public: string strFormat(string a) { int cnt = 1; string str = ""; int len = a.length(); if (len == 1) return "1" + a; for (int j = 1; j < len; j++) { if (a[j - 1] == a[j]) { cnt++; } else { str = str + static_cast<char>(cnt + '0') + a[j - 1]; cnt = 1; } if (j == len - 1) { str = str + static_cast<char>(cnt + '0') + a[j]; } } return str; } string countAndSay(int n) { if (n == 1) return "1"; string a = "1"; for (int i = 0; i < n-1; i++) { a = strFormat(a); } return a; } };