leetcode:38. 外观数列

题目来源

题目描述

在这里插入图片描述

class Solution {
public:
    string countAndSay(int n) {

    }
};

总的来讲,就是对前1个数进行报数

题目解析

看懂题目的第一个想法:需要递归,因为后一项都和前一项有关

class Solution {
public:
    string countAndSay(int n) {
        if(n == 1){
            return "1";
        }

        std::string lastStr = countAndSay( n - 1);
        std::string ans;
        int  len = lastStr.size(), left = 0;
        for (int read = 0; read < len; ++read) {
            if(read == len - 1 || lastStr[read] != lastStr[read + 1]){  //到了末尾或者到了边缘
                ans.append(std::to_string(read - left + 1)).push_back(lastStr[left]);
                left = read + 1;
            }
        }
        return ans;
    }
};
class Solution {
public:
	string countAndSay(int n) {
	    if(n == 1){
	        return "1";
	    }
	    string lastStr = countAndSay(n - 1);
	    string ans;
	    int i = 0, j = 1, len = lastStr.size();
	    while(j < len) {
	        if(lastStr[i] != lastStr[j]){
	            ans.append(to_string(j - i)).push_back(lastStr[i]);
	            // ans = ans + to_string(j - i) + lastStr[i];
	            i = j;
	        }
	        j++;
	    }
	    ans.append(to_string(j - i)).push_back(lastStr[i]);
	    return ans;
	}

}

在这里插入图片描述

class Solution {
    std::string helper(std::string s){
        std::string  ans;
        int len = s.length();
        int  i = 0;
        while (i < len){
            char ch = s[i];
            int k = i + 1, cnt = 1;
            while (k < len && s[k] == ch){
                ++cnt;
                ++k;
            }
            ans.append(std::to_string(cnt)).push_back(ch);
            i = k;
        }

        return ans;
    }
public:
    string countAndSay(int n){
        std::string  ans = "1";
        for (int i = 1; i < n; ++i) {
            ans = helper(ans);
        }
        return ans;
    }
};

在这里插入图片描述

类似题目

题目思路
leetcode:38. 外观数列 Count and Say
leetcode:443. 压缩字符串—重复字符串变为字符+重复次数 String Compression双指针
leetcode:271.字符串的编码与解码 Encode and Decode Strings在每个字符串的后面加上换行字符 ‘\0’,其还属于一个字符串,这样在解码的时候,只要去查找这个换行字符就可以了
leetcode:297. 二叉树的序列化与反序列化要解决两个问题:1. 怎么区分节点(节点和节点之间、节点与null节点):使用#等特殊标记每一个null,使用,等字符串区分每一个节点;2. 怎么编码:序列化时:前序遍历,根节点–>左节点–>右节点;反序列化:前序遍历,先构建出根节点 ,然后构建左节点,再构建右节点(每构建一个节点,都需要从原始字符中移除)(选择前序遍历,是因为 根->左->右、 根->左->右的打印顺序,在反序列化时更容易定位出根节点的值。)