2ms c++ iterative solution


  • 0
    K
    class Solution {
    public:
        string countAndSay(int n) {
        	string result = "";
        	string temp;
        	if (n > 0) {
        		char* cPtr;
        		char* prevCPtr;
        		int sameDigitCount = 1;
        		for (int i = 0; i < n; i++) {
        			if (i == 0) {
        				result += intToChar(1);
        			} else {
        				cPtr = &result[0];
        				prevCPtr = &result[0];
        				temp = "";
        				while (*cPtr != '\0') {
        					cPtr++;
        					if (*cPtr == *prevCPtr)
    	    					sameDigitCount++;
        					else {
        					    temp += intToChar(sameDigitCount);
        						temp += *prevCPtr;
        						prevCPtr += sameDigitCount;
        						sameDigitCount = 1;
        					}
        				}
        				result = temp;
        			}
        		}
        	}
        	return result;
        }
    
        char intToChar(int digit) {
        	char result;
        	switch (digit) {
        		case 0:
        			result = '0';
        			break;
        		case 1:
        			result = '1';
        			break;
        		case 2:
        			result = '2';
        			break;
    	    	case 3:
        			result = '3';
        			break;
        		case 4:
        			result = '4';
        			break;
        		case 5:
        			result = '5';
        			break;
        		case 6:
        			result = '6';
        			break;
        		case 7:
        			result = '7';
        			break;
        		case 8:
        			result = '8';
        			break;
        		case 9:
        			result = '9';
        			break;
        		default:
        			cout << "Error, unknown character passed.";
        			result = '\0';
        			break;
        	}
    	    return result;
        }
    };

Log in to reply
 

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