(字符串)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;
        }
    };

     

posted @ 2017-01-26 15:20  Kobe10  阅读(272)  评论(0编辑  收藏  举报