LeetCode-Count and Say

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) {
         // Start typing your C/C++ solution below
         // DO NOT write int main() function
         vector<string> a;
         stringstream ss2;
         a.push_back("1");
         string s;
         string o,o1;
         for(int i=1;i<n;i++){
             s=a[i-1];
             char current=s[0];
             int count=1;
             o.clear();
             for(int j=1;j<s.length();j++){
                 if(s[j]!=current){
                     ss2.clear();
                     ss2<<count;
                     o1.clear();
                     ss2>>o1;
                     o+=o1;
                     o+=current;
                     current=s[j];
                     count=1;
                 }
                 else{
                     count++;
                 }
             }
             ss2.clear();
             ss2<<count;
             o1.clear();
             ss2>>o1;
             o+=o1;
             o+=current;
             a.resize(a.size()+1);
             a[a.size()-1]=o;
         }
         return a[a.size()-1];
     }
 };

 

posted @ 2013-09-22 23:18  懒猫欣  阅读(153)  评论(0编辑  收藏  举报