Leetcode#38count and Say

Source: Internet
Author: User

The Count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

1is read off as"one 1"Or11.
11is read off as"two 1s"Or21.
21is read off as"one 2, thenone 1"Or1211.

Given an integer n, generate the nth sequence.

Note:the sequence of integers would be represented as a string.

Analysis, the iteration solves the result of nth time, so starting with the first "1" iteration, the last resulting string is re-expressed in the above form

public class Solution {

Public String Countandsay (int n) {

if (n = = 1) {

return "1";

}

String s = "1";

StringBuffer ret = new StringBuffer ();

int cnt = 0;

int round = 0; How many times round is an iteration

int i;

while (++round < n) {

CNT = 1;

Ret.setlength (0);

for (I=1; I<s.length (); i++) {

if (S.charat (i) = = S.charat (i-1)) {//duplicate value, continue count

cnt++;

}else{//A new value appears, recorded to RET

Ret.append (CNT). Append (S.charat (i-1));

CNT = 1; Reset CNT

}

}

Ret.append (CNT). Append (S.charat (i-1));

s = ret.tostring (); Update S

}

return ret.tostring ();

}

}


Leetcode#38count 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.