Count and Say
Total Accepted: 63607 Total Submissions: 237192 Difficulty: Easy
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) { string s = ""; string res = s; for(int i=0;i<n;i++){ res = ""; int cnt = 1; for(int j=1;j<s.size();j++){ if(s[j]==s[j-1]){ cnt++; }else{ res.push_back(cnt+'0'); res.push_back(s[j-1]); cnt = 1; } } res.push_back(cnt+'0'); if(!s.empty()) res.push_back(s[s.size()-1]); s = res; } cout<<res<<endl; return res; } };
Next challenges: (M) Encode and Decode Strings
写者:zengzy
出处: http://www.cnblogs.com/zengzy
标题有【转】字样的文章从别的地方转过来的,否则为个人学习笔记
 
                    
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号