My solution in C++


  • 0
    N
    class Solution {
    public:
        string countAndSay(int n) {
         string prev, result = "1";
    		int count;
    		char lastVal;
    		for (int i = 2; i <= n; i++) {
    			prev = result;
    			result.clear();
    			count = 1;
    			lastVal = prev[0];
    			unsigned int j = 1;
    			for (; j < prev.size(); j++) {
    				if (prev[j] == lastVal) {
    					count++;
    				} else {
    					result.push_back(count + '0');
    					result.push_back(lastVal);
    
    					lastVal = prev[j];
    					count = 1;
    				}
    
    			}
    			result.push_back(count + '0');
    			result.push_back(lastVal);
      		}
    		return result;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.