您的位置:首页 > 其它

38. Count and Say

2016-06-30 16:04 281 查看
题目:

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.

题意:

给定一个整数n,生成第n个如以上所示的序列,

 1.     1

 2.     11

 3.     21

 4.     1211

 5.     111221 

 6.     312211

 7.     13112221

 8.     1113213211

 9.     31131211131221

 10.   13211311123113112211

 …     … 

 n      n

思路:

基于以上题意说明,用代码实现题意所示的生成过程即可。每一次生成序列只需要对上一次生成的序列count and say即可。

代码:C++版:4ms

class Solution {
public:
    string countAndSay(int n) {
        if (n == 0) return "";
        string res = "1";
        while (--n) {  //找到第n个序列
            string cur = "";
            for (int i=0; i<res.size(); i++) {  //轮训前一次生成的字符串
                int count = 1;
                while ((i+1 < res.size()) && (res[i] == res[i+1])){  //对相同的数字进行计数
                    count++;
                    i++;
                }
                cur += to_string(count) + res[i];  //组拼count_and_say
            }
            res = cur;
        }
        return res;
    }
};
代码:Java版:20ms
public class Solution {
    public String countAndSay(int n) {
        String result = "1";
        
        for (int outer=1; outer<n; outer++) {
            String previous = result;
            result = "";
            int count = 1;
            char say = previous.charAt(0);
            
            for (int i=1; i<previous.length(); i++) {
                if (previous.charAt(i) != say) {
                    result = result + count + say;
                    count = 1;
                    say = previous.charAt(i);
                } else count++;
            }
            result = result + count + say;
        }
        
        return result;
    }
}

代码:C++版:0ms 用时最短

class Solution {
public:
    string countAndSay(int n) {
        string str = "1";
        for (int i=1; i<n; i++) {
            str = helper(str);
        }
        return str;
    }
    
    string helper(string s) {
        char c = s[0];
        int count = 1;
        stringstream ss;
        for (int i=1; i<s.size(); i++) {
            if (s[i] != c) {
                ss << count << c;
                c = s[i];
                count = 1;
            } else {
                count++;
            }
        }
        ss << count << c;
        return ss.str();
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: