Wednesday, April 10, 2013

Count and say (C++ code)

LeetCode Count and Say, Mar 6 '12
 难度2,出现频率2
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.

  string countAndSay(int n) {
       if(n == 0) return "";
       if(n ==1)  return "1";
       string str;
       string prev = countAndSay(n-1);
       int count = 1, i = 0;

       for(i = 0; i < prev.length() - 1; i++){
           if(prev[i] != prev[i+1]) {    
                str.append(to_string(count));
                str.push_back(prev[i]);
                count = 1;
           }

          else count++;
       }

      str.append(to_string(count));
      str.push_back(prev[i]);

      return str;     
    }

No comments:

Post a Comment