38. Count and Say

╰+哭是因爲堅強的太久メ 2021-10-18 10:48 395阅读 0赞

description:

就是看前面那个数有几个几,然后写一串。
Note:

Example:

  1. The count-and-say sequence is the sequence of integers with the first five terms as following:
  2. 1. 1
  3. 2. 11
  4. 3. 21
  5. 4. 1211
  6. 5. 111221
  7. 1 is read off as "one 1" or 11.
  8. 11 is read off as "two 1s" or 21.
  9. 21 is read off as "one 2, then one 1" or 1211.

answer:

  1. class Solution {
  2. public:
  3. string countAndSay(int n) {
  4. if (n < 0) return "";
  5. string res = "1";
  6. for (int i = 1; i < n; i++) {
  7. string newres = "";
  8. for (int k = 0; k < res.size(); ++k) {
  9. int cnt = 1;
  10. while(k + 1 < res.size() && res[k] == res[k +1]){
  11. cnt += 1;
  12. ++k;
  13. }
  14. newres += to_string(cnt) + res[k];
  15. }
  16. res = newres;
  17. }
  18. return res;
  19. }
  20. };

relative point get√:

  • to_string() c++中string类的内置函数

hint :

转载于:https://www.cnblogs.com/forPrometheus-jun/p/11124815.html

发表评论

表情:
评论列表 (有 0 条评论,395人围观)

还没有评论,来说两句吧...

相关阅读