Title:
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"
Or11
.
11
is read off as"two 1s"
Or21
.
21
is 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.
Test Instructions:
The Count-and-say sequence is a set of integer numbers as shown in the following polygons:
1, 11, 21, 1211, 111221, ...
1
Read as "one 1" or 11.
One read "Two 1" or a.
read as "One 2", and "one 1" or 1211.
Given an integer n, produces the nth sequence.
Note: This generated sequence of integers should be represented by a string.
Algorithm Analysis:
* The topic is really not clear ...
* To explain is, enter N, then I'll hit the nth line string.
* How to determine the nth line string? This one of his is regular.
* n = 1 o'clock, prints a 1.
* n = 2 o'clock, see n=1 that line, read: A 1, so print: 11.
* n = 3 o'clock, see n=2 that line, read: 2 1, so print: 21.
* n = 4 o'clock, see n=3 that line, read: A 21 1, so print: 1211.
And so on (note here that n is starting from 1)
The problem is not difficult, directly on the code
AC Code:
public class Solution { public String Countandsay (int n) { String subres = ""; if (n==1) return "1"; int sn = 2; String subinput= "1"; while (sn<=n) { Subres=subsountandsay (subinput); Subinput=subres; sn++; } return subres; } Private string Subsountandsay (string n) {string res = ""; String oristring= N; char tem; int i = 0; int startindex=0; int k=0; while (I<oristring.length ()) { k=0; Tem= ' + '; while (I<oristring.length ()) { if (Oristring.charat (startindex) ==oristring.charat (i)) { k ++; Tem=oristring.charat (i); i++; } else { startindex=i; break; } } Res+=integer.tostring (k) +tem; } return res; }}
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Count and Say