Leetcode Problem Solving report--Count and Say

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.