My C++ Solution


  • 0
    class Solution {
    public:
    	string countAndSay(int n) {
    		if (n == 0) return "";
    		else{
    			string res = "1",temp;
    			int count = 0;
    			char com;
    			for (int i = 1; i < n; i++){
    				for (int j = 0; j < res.size(); ){
    					com = res[j];
    					while (res[j] == com && j< res.size()){
    						++count;
    						++j;
    					}
    					temp = temp + char(count + '0') + com;
    					count = 0;
    				}
    				res = temp;
    				temp = "";
    			}
    			return res;
    		}
    	}
    };

  • 0
    L

    class Solution {
    public:
    string countAndSay(int n) {
    if (n < 1)
    {
    return "0";
    }

    	string ret = "1";
    	while (--n > 0)
    	{
    		ret = countSay(ret);
    	}
    
    	return ret;
    }
    
    string countSay(string& input) {
    	string ret;
    	int i = 0;
    	int count = 1;
    	while (i + 1 < input.size()) {
    		if (input[i] == input[i+1]) {
    			++count;
    			++i;
    			continue;
    		}
    
    		ret.push_back(count + '0');
    		ret.push_back(input[i]);
    		count = 1;
    		++i;
    	}
    
    	ret.push_back(count + '0');
    	ret.push_back(input[i]);
    	return ret;
    }
    

    };


Log in to reply
 

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