详细思路

遍历数组,从n=2开始,用num表示当前数字,cnt表示当前数字出现次数,i不断遍历字符串,当遇到不一样的字符时num和cnt保存在temp数组,遍历完temp赋值给字符串
 
精确定义
ans 用来遍历
temp 用来记录,并在遍历结束更新ans
i当前判断到哪个n
j需要判断的字符
num当前判断的数字
cnt当前判断的数字出现的次数
class Solution {
public:
    string countAndSay(int n) {
        string ans="1";
        if(n==1)return ans;
        for(int i=2;i<=n;i++){
            string temp="";
            char num=ans[0];
            char cnt='1';
            for(int j=1;j<ans.size();j++){
                if(ans[j]==num)cnt++;
                else {
                    temp+=cnt;
                    temp+=num;
                    num=ans[j];
                    cnt='1';
                }
            }
            temp+=cnt;
            temp+=num;
            ans=temp;
        }
        return ans;
    }
};
踩过的坑
            temp+=cnt;
            temp+=num;最后还需要再补充temp一次

 

posted on 2021-07-27 22:45  offer快到碗里来~  阅读(58)  评论(0)    收藏  举报