Topic:
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.
One is read off as "1s" or 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 would be represented as a string.
Click to solve the problem: Count and Say
Analysis: Test instructions is required to generate a set of strings that meet test instructions requirements through the program,
The problem is not high, the basic idea is: take n for example, directly from left to right scan n-1 string, calculate the number of the same number, until the end of the scan! As follows: initial: Count = 1, count++ for each occurrence of the same number, and then convert count to string or character type + current array character to find the nth string as a rule.
Java code: Accepted
Public classSolution { PublicStringCountandsay(intN) {String NewS ="1";intCount =1;inti =1; while(I < N) {String s = NewS; NewS =""; for(intj =0; J < S.length (); j + +) {if(j +1) < S.length () && S.charat (j) = = S.charat (j +1)) {count + +; }Else{News = news + Count + s.charat (j); Count =1; }} i + +; }returnNewS; }}
Python Code Accepted
class solution(object): def Countandsay(self, n): "" : Type N:int:rtype:str "" "i =1Count =1NewS ="1" whileI < n:s= news news ="" forJinchRange (len (s)):if(j +1) < Len (s) andS[J] = = S[j +1]): Count = Count +1 Else: News = news + str (count) + s[j] Count =1i = i +1 returnNewS
Leetcode Problem Solving report--Count and Say