LeetCode 38. Count and Say
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 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 term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"
题意:
当n=1,str="1"
当n=2,因为当n=1时,str="1",里面有一个“1”,所以此时的str="11"
当n=3,因为当n=2时,str="11",里面有两个“1”,所以此时的str="21"
当n=4,因为当n=3时,str="21",里面有一个"2",一个“1”,所以此时的str="1211"
当n=5,因为当n=4时,str="1211",里面是:先一个"1",再一个"2",最后两个“1”,所以此时的str="111221"
即:第i+1个字符串是第i个字符串的读法。
思路:直接模拟解决,代码如下:
String s = "1"; int count = 1, j; StringBuilder str = new StringBuilder(); for(int i = 2; i <= n; i++){ for(j = 0; j < s.length(); j++){ while(j + 1 < s.length() && s.charAt(j) == s.charAt(j + 1)){ j++; count++; } str.append(Integer.toString(count) + s.charAt(j)); count = 1; } s = str.toString(); str.delete(0, str.length()); } return s; }