• (字符串)count and say


    • https://www.nowcoder.com/practice/c5e8e84b62bb48398ec3c88153950fb5?tpId=46&tqId=29141&tPage=3&rp=3&ru=/ta/leetcode&qru=/ta/leetcode/question-ranking


    • 题意:这个题目的意思是,输入一个整数n,输出第n-1个字符串怎么读的串。
      输入n=1:“1”表示一个1
      输入n=2:读出这个“1”,一个1用"11"表示。输入n=3:读出"11",两个1,用"21"表示。
      依次类推,输入n,第n-1个字符串的读法。

    • 思路:这个题目很显然要用到迭代法,从第一个开始进行迭代。n进行循环处理,传入一个要读的字符串,将这个字符串循环处理,找到相同的字符并且计数,然后将他们加入字符串,返回一个读过的字符串即可。
    • 代码:
      class Solution {
      public:
          string countAndSay(int n) {
              if(n == 0)return string("");
              string res("1");
              for(int i = 1; i < n; i++) {
                  res = build(res);
              }
              return res;
          }
          string build(const string& res) {
              string ret;
              int len = res.size();
              for(int i = 0; i < len; i++) {
                  int count = 1;
                  char x = res[i];
                  while(i < len && res[i+1]==x) {
                      count++;
                      i++;
                  }
                  ret.push_back(count+'0');
                  ret.push_back(x);
              }
              return ret;
          }
      };
  • 相关阅读:
    mysql 查询优化 ~ select count 知多少
    mongodb 案例 ~ 经典故障案例
    printk 驱动调试
    21天学通C++学习笔记(七):函数
    OPC UA
    MQTT
    分库分表
    水平、垂直权限问题(横向越权与纵向越权)
    数据库中的行转列和列转行
    面试知识点
  • 原文地址:https://www.cnblogs.com/Kobe10/p/6351638.html
Copyright © 2020-2023  润新知