Medium

题目描述

「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。

你可以将其视为字符串的行程长度编码(Run-Length Encoding,RLE)。行程长度编码是一种字符串压缩方法,通过将连续的相同字符(重复 2 次或更多次)替换为字符和标记重复次数的数字串联来工作。

前五项如下:

1.     1
2.     11
3.     21
4.     1211
5.     111221

第一项是数字 1。

描述前一项,这个数是 1 即 “一个 1”,记作 “11”。

描述前一项,这个数是 11 即 “两个 1”,记作 “21”。

描述前一项,这个数是 21 即 “一个 2 + 一个 1”,记作 “1211”。

描述前一项,这个数是 1211 即 “一个 1 + 一个 2 + 两个 1”,记作 “111221”。

描述 一个数字字符串,首先要将字符串分割为 最小 数量的组,每个组都由连续的相同字符组成。然后对于每个组,先描述字符的数量,然后描述字符本身,形成一个描述组。要将描述转换为数字字符串,先将每组中的字符数量用数字替换,再将所有描述组连接起来。

给定一个正整数 n,返回外观数列的第 n 项。

示例 1:

输入:n = 4
输出:"1211"
解释:
countAndSay(1) = "1"
countAndSay(2) = 读 "1" = 一个 1 = "11"
countAndSay(3) = 读 "11" = 两个 1 = "21"
countAndSay(4) = 读 "21" = 一个 2 + 一个 1 = "1211"

示例 2:

输入:n = 1
输出:"1"
解释:这是一个基础情况。

提示:

  • 1 <= n <= 30

**进阶:**你能否用迭代方法解决这个问题?

解题思路

这是一个典型的字符串模拟题目,核心思路是按照题目描述的规则逐步构建序列。

基本思路:

  1. 从基础情况 “1” 开始
  2. 对于第 i 项,需要读取第 i-1 项并进行行程长度编码
  3. 遍历当前字符串,统计连续相同字符的个数
  4. 将个数和字符拼接形成下一项

具体实现步骤:

  1. 如果 n = 1,直接返回 “1”
  2. 初始化结果为 “1”
  3. 从第 2 项开始,重复 n-1 次:
    • 遍历当前字符串
    • 用双指针或计数的方式统计连续字符
    • 将计数和字符添加到新字符串中
    • 更新结果为新字符串

优化要点:

  • 使用 StringBuilder 或字符串拼接优化性能
  • 一次遍历完成计数和构建新字符串
  • 避免重复的字符串操作

时间复杂度主要取决于生成的字符串长度,空间复杂度为当前字符串的长度。

代码实现

class Solution {
public:
    string countAndSay(int n) {
        string result = "1";
        
        for (int i = 2; i <= n; i++) {
            string next = "";
            int count = 1;
            char currentChar = result[0];
            
            for (int j = 1; j < result.length(); j++) {
                if (result[j] == currentChar) {
                    count++;
                } else {
                    next += to_string(count) + currentChar;
                    currentChar = result[j];
                    count = 1;
                }
            }
            next += to_string(count) + currentChar;
            result = next;
        }
        
        return result;
    }
};
class Solution:
    def countAndSay(self, n: int) -> str:
        result = "1"
        
        for i in range(2, n + 1):
            next_str = ""
            count = 1
            current_char = result[0]
            
            for j in range(1, len(result)):
                if result[j] == current_char:
                    count += 1
                else:
                    next_str += str(count) + current_char
                    current_char = result[j]
                    count = 1
            
            next_str += str(count) + current_char
            result = next_str
        
        return result
public class Solution {
    public string CountAndSay(int n) {
        string result = "1";
        
        for (int i = 2; i <= n; i++) {
            StringBuilder next = new StringBuilder();
            int count = 1;
            char currentChar = result[0];
            
            for (int j = 1; j < result.Length; j++) {
                if (result[j] == currentChar) {
                    count++;
                } else {
                    next.Append(count).Append(currentChar);
                    currentChar = result[j];
                    count = 1;
                }
            }
            next.Append(count).Append(currentChar);
            result = next.ToString();
        }
        
        return result;
    }
}
/**
 * @param {number} n
 * @return {string}
 */
var countAndSay = function(n) {
    let result = "1";
    
    for (let i = 1; i < n; i++) {
        let newResult = "";
        let count = 1;
        let currentChar = result[0];
        
        for (let j = 1; j < result.length; j++) {
            if (result[j] === currentChar) {
                count++;
            } else {
                newResult += count + currentChar;
                currentChar = result[j];
                count = 1;
            }
        }
        newResult += count + currentChar;
        result = newResult;
    }
    
    return result;
};

复杂度分析

复杂度类型复杂度说明
时间复杂度O(2^n)每一项的长度大致是前一项的两倍,总长度呈指数增长
空间复杂度O(2^n)需要存储当前项和下一项的字符串

相关题目