码迷,mamicode.com
首页 > 其他好文 > 详细

(字符串)count and say

时间:2017-01-26 15:42:41      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:表示   char   迭代   style   int   题意   cti   const   意思   

  • 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;
        }
    };

     

(字符串)count and say

标签:表示   char   迭代   style   int   题意   cti   const   意思   

原文地址:http://www.cnblogs.com/Kobe10/p/6351638.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!