题目来源:https://leetcode.com/problems/count-and-say/
问题描述
38. Count and Say
Easy
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 where 1 ≤ n ≤ 30, 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"
------------------------------------------------------------
题意
给定一个由数字组成的字符串,按照数字的读法写出写一个字符串。
------------------------------------------------------------
思路
用两个指针pre和cur遍历字符串分别保存之前的字符和当前字符,再用cnt统计截止到cur,pre字符出现的次数。特别注意字符串首端和字符串尾端的处理。
------------------------------------------------------------
代码
class Solution {
public String countAndSay(int n) {
if (n == 0)
{
return "";
}
if (n == 1)
{
return "1";
}
StringBuilder sb = new StringBuilder("1");
int i = 1, len = 0, j = 0, cnt = 0;
char cur = 0, pre = 0;
for (i=2; i<=n; i++)
{
len = sb.length();
cnt = 0;
pre = 0;
cur = 0;
StringBuilder sb1 = new StringBuilder();
for (j=0; j<len; j++)
{
cur = sb.charAt(j);
if (pre == 0)
{
pre = cur;
}
else if (cur == pre)
{
cnt++;
}
else
{
char chcnt = (char)(cnt+'1');
sb1.append(chcnt);
sb1.append(pre);
cnt = 0;
pre = cur;
}
}
char chcnt = (char)(cnt+'1');
sb1.append(chcnt);
sb1.append(cur);
sb = sb1;
}
return sb.toString();
}
}