[LeetCode]Count and Say

来源:互联网 发布:银行卡数据采集器 编辑:程序博客网 时间:2024/06/05 01:04

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 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 sequence.

Note: The sequence of integers will be represented as a string.

对这个序列持续读写,找好规律即可。

class Solution {public:    string countAndSay(int n) {        if(n==1)            return "1";        string ret = "1";        for(int i = 1; i<n; ++i){            ret = nextString(ret);        }        return ret;    }    string nextString(string s){        char temp = s[0];        s = s+'a'; //边界点        string ret;        int index = 1;        for(int i=1; i<s.length(); ++i){            if(s[i]==temp){                index++;            }            else{                char count = '0'+index;                ret = ret+count;                ret = ret+temp;                index = 1;                temp = s[i];            }        }        return ret;    }};



0 0
原创粉丝点击