LeetCode: Count and Say

来源:互联网 发布:js 调用随机数 编辑:程序博客网 时间:2024/05/21 11:33

#include<iostream>#include<vector>#include<queue>#include<string>#include<stdlib.h>#include <sstream>#include<windows.h>using namespace::std;class Solution {public:    string countAndSay(int n) {        // Start typing your C/C++ solution below        // DO NOT write int main() functionif(n == 1)return "1";else{return pronouce(countAndSay(n - 1).c_str());}    }string pronouce(string value){int index = 0;string result;//stringstream ss;//string result;int count = 1;int size = value.size();char cur = value[0];for(int i = 1; i < size; i++){if(cur == value[i]){count++;}else{result += count + '0';result += cur;count = 1;}cur = value[i];}result += count + '0';result += cur;return result;}};


Study Point:

巧设起始点,则只要用一个for loop

Round 2:

class Solution {public:    string countAndSay(int n) {        string pre = "1";        string cur = "";        for(int i = 2; i <= n; i++)        {            char count = '1';            char say = pre[0];            for(int j = 1; j < pre.size(); j++)            {                if(pre[j] == say)                    count++;                else                {                    cur = cur + count + say;                    count = '1';                    say = pre[j];                }            }            cur = cur + count + say;            pre = cur;            cur = "";        }        return pre;    }};

Round 3:

class Solution {public:    string countAndSay(int n) {        string result = "1";        n--;        while(n > 0)        {            int l = 0 , r = 0;            string temp;            while(l < result.size())            {                int count = 0;                while(r < result.size() && result[r] == result[l])                {                    r++;                    count++;                }                temp += to_string(count);                temp += result[l];                l = r;            }            result = temp;            n--;        }        return result;    }};