LeetCode solution report -- Count and Say

Source: Internet
Author: User

LeetCode solution report -- Count and Say

Question:

The count-and-say sequence is the sequence of integers
Beginning as follows:
1, 11, 21,121 1, 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.
Click to solve the problem: Count and Say

Analysis: the meaning of the question is to generate a set of strings that meet the requirements of the question through the program,
The question is not very difficult. The basic idea is: Take n as an example, scan the n-1 string from left to right, calculate the number of identical numbers until the scan ends! Initial: count = 1. Each time a number is the same, count ++ converts count to a string or character type + the current array character to find the nth string.

Java code: Accepted

public class Solution {    public String countAndSay(int n) {       String newS = "1";       int count = 1;       int i = 1;       while(i < n){           String s = newS;           newS = "";           for(int j = 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 ++;       }       return newS;    }}

Python code Accepted

class Solution(object):    def countAndSay(self, n):        """        :type n: int        :rtype: str        """        i = 1        count = 1        newS = "1"        while i < n:            s= newS            newS = ""            for j in range(len(s)):                if((j + 1) < len(s) and s[j] == s[j + 1]):                    count = count + 1                else:                    newS = newS + str(count) + s[j]                    count = 1            i = i + 1        return newS

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.