LeetCode Top Interview Questions 38. Count and Say (Java版; Easy)

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6


​welcome to my blog​

LeetCode Top Interview Questions 38. Count and Say (Java版; Easy)

题目描述

The count-and-say sequence is the sequence of integers with the first five terms as following:

1. 1
2. 11 读出上一组数: 1个1, 记作11
3. 21 读出上一组数: 2个1, 记作21
4. 1211 读出上一组数: 1个2,1个1, 记作1211
5. 111221 读出上一组数: 1个1,1个2,2个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 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"

第一次做; 使用cur翻译pre; 自底向上, 也就是从1到n; 双层循环+双变量pre,cur; 循环条件的优化将for(int j=1; j<pre.length(); j++)改进成for(int j=1, len=pre.length(); j<len; j++)

class Solution {
public String countAndSay(int n) {
//细节:这样的初始化
StringBuilder pre;
StringBuilder cur = new StringBuilder("1");
int count;
char ch;
//自底向上
for(int i=2; i<=n; i++){
//用cur描述pre
pre = cur;
cur = new StringBuilder();
//
ch = pre.charAt(0);
count = 1;
//1ms的优化, 将for(int j=1; j<pre.length(); j++)改进成for(int j=1, len=pre.length(); j<len; j++)
for(int j=1, len=pre.length(); j<len; j++){
if(ch == pre.charAt(j)){
count++;
}
else{
cur.append(count).append(ch);
//update
ch = pre.charAt(j);
count = 1;
}
}
//细节: 需要在内循环结束后再单独更新一次cur
cur.append(count).append(ch);
}
return cur.toString();
}
}


阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Java