[LeetCode]Count and Say

来源:互联网 发布:mysql distinct 用法 编辑:程序博客网 时间:2024/06/03 20:36
解题思路:
把题目描述,翻译成 C++语言即可

提示一点:容易遗漏最后一组 count and say, 因为在inner-for循环中,其判断条件并不包含str遍历结束 


class Solution {public:    string countAndSay(int n) {        string ret = "";        for (int i = 0; i < n; ++i){            if (i == 0){                ret = "1";                continue;            }            int count = 0;            string strRet;            int j;            for (j = 0; j < ret.length(); ++j){                if (j == 0){                    count = 1;                    continue;                }                if (ret[j] != ret[j-1]){                    strRet += toString(count) ;                    strRet += ret[j-1];                    count = 1;                }else{                    count ++;                }            }          // 容易遗漏            if ( count != 0 ){                strRet += toString(count);                strRet += ret[j-1];            }            ret = strRet;        }        return ret;    }    string toString(int count){        stringstream ss;        ss << count;        string ret = ss.str();        ss.str("");        return ret;    }};


0 0