#38. Count and Say

来源:互联网 发布:阿里云及产品体系介绍 编辑:程序博客网 时间:2024/06/10 23:34

题目描述:

The count-and-say sequence is the sequence of integers with the first five terms as following:

  1. 1
  2. 11
  3. 21
  4. 1211
  5. 111221
    1 is read off as “one 1” or 11.
    11 is read off as “two 1s” or 21.
    21 is read off as “one 2, then one 1” or 1211.
    Given an integer n, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

找规律模拟的题,考逻辑。

class Solution {public:    string countAndSay(int n) {        if(n==1)            return "1";        else            return iteration("1",1,n);    }    string iteration(string s,int k,int n){        //cout<<"k = "<<k<<" "<<"s = "<<s<<endl;        if(k==n)            return s;        string result;        int i,j;        for(i=0;i<s.size();){            j=i;            while(j<s.size()&&s[i]==s[j])                j++;            result.push_back(j-i+'0');            result.push_back(s[i]);            i=j;            //cout<<"result = "<<result<<endl;        }        return  iteration(result,k+1,n);    }};

本身是一个迭代的过程