zoukankan      html  css  js  c++  java
  • (字符串)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执行顺序
    读取资源文件ResourceUtils
    军规(一)
    Spring声明式事务@Transactional 详解,事务隔离级别和传播行为
    linux crontab
    es _cat API
    elastic search 常用查询
    elastic search 重要的系统配置
    cerebro 配置
    Ubuntu18.04 搭建zookeeper单机版集群
  • 原文地址:https://www.cnblogs.com/Kobe10/p/6351638.html
Copyright © 2011-2022 走看看