Count And Say

Q: 

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.

A:简单题,直接模拟即可,int转换成string的方法注意一下:

 

int cnt = 1;

                stringstream ss;
                 ss<<cnt;
          string s = ss.str();
    string countAndSay(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
                
        if(n<=1)
            return "1";
        
        string res;
        string tmp = "1";
        int i,j;
        int cnt;
        char prevc;
        int len;
        
        for(i=2;i<=n;i++)
        {
            res = "";
            cnt = 0;
            prevc = tmp[0];
            for(j=0;j<tmp.size();j++)
            {                    
                if(tmp[j]==prevc)
                    cnt++;
                else
                {
                    stringstream ss;
                    ss<<cnt;
                    res = res + ss.str() + prevc;
                    prevc = tmp[j];
                    cnt = 1;
                }
            }
            
            if(cnt>0)
            {
                stringstream ss;
                ss<<cnt;
                res = res + ss.str() + prevc;
            }
            
            tmp = res;
        }
        
        return res;
        
    }

  

posted @ 2013-09-24 20:35  summer_zhou  阅读(136)  评论(0编辑  收藏  举报