[leetcode]50 Count and Say

来源:互联网 发布:广州艺知艺术培训学校 编辑:程序博客网 时间:2024/06/06 20:24

题目链接:https://leetcode.com/problems/count-and-say/
Runtimes:12ms

1、问题

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.

2、分析

数并且说出来,题目简单,请看英文实例~

3、小结

严谨的思路~

4、实现

class Solution {public:    string change(int n)    {        string s = "";        if (n >= 0 && n <= 9)            return s += (n + '0');        while (n > 0)        {            s += (n % 10) + '0';            n /= 10;        }        int i = 0, j = s.length() - 1;        while (i < j)        {            char c = s[i];            s[i] = s[j];            s[j] = c;        }        return s;    }    string countAndSay(int n) {        if (n <= 0)            return "";        int i = 1;        string result = "1";        while (i < n)        {            string tmp = "";            int j = 1, start = 0;            for (; j < result.length(); ++j)            {                if (result[j] != result[start]){                    tmp = tmp + change(j - start) + result[start];                    start = j;                }            }            tmp += change(j - start) + result[start];            result = tmp;            //cout << result << endl;            ++i;        }        return result;    }};

5、反思

好像可以跑得更快的!待改进~

0 0
原创粉丝点击