解题思路:从第一个一次遍历统计每个字符出现的次数以及当前字符,然后将其赋值给变量,最终将变量返回。提供C++和python的官方代码
#
# @lc app=leetcode.cn id=38 lang=python3
#
# [38] 外观数列
#
# @lc code=start
class Solution:
def countAndSay(self, n: int) -> str:
prev = '1'
for i in range(n-1):
curr = ""
pos = 0
start = 0
while pos < len(prev):
while pos < len(prev) and prev[pos] == prev[start]:
pos += 1
curr += str(pos-start)+prev[start]
start = pos
prev = curr
return prev
# @lc code=end
class Solution {
public:
string countAndSay(int n) {
string prev="1";
for (int i=2;i<=n;++i){
string curr="";
int start=0;
int pos=0;
while(pos<prev.size()){
while (pos<prev.size()&&prev[pos]==prev[start]){
pos++;
}
curr+=to_string(pos-start)+prev[start];
start=pos;
}
prev=curr;
}
return prev;
}
};