count and say leetcode c++

来源:互联网 发布:虚拟实验室软件下载 编辑:程序博客网 时间:2024/06/14 04:01

pay attention to n and the string.

it is easy to understand the code below.

class Solution {public:    string countAndSay(int n) {          // Start typing your C/C++ solution below          // DO NOT write int main() function          if(n< 0) return NULL;          string seq = "1";          for(int i = 1; i < n; ++i)          {              //cout<<seq<<endl;              string tmp = "";              int count=0;              char current=seq[0];              int index = 0;              while(index < seq.length())              {                  if(seq[index] == current)                      count++;                  else                  {                      tmp += to_string(count) + current;                      current = seq[index];                      count = 1;                  }                  index++;              }              tmp += to_string(count) + current;              seq = tmp;          }          return seq;      }};

0 0
原创粉丝点击