class Solution {
public:
string countAndSay(int n) {
if( n <= 0){
return NULL;
}
string dp[n];
dp[0] = "1";
string now;
string newstr;
for(int i = 1 ; i < n ; i++){
int count = 1;
now = dp[i-1];
newstr = "";
int len = now.size();
for(int j = 1 ; j < len ; j++){
//如果和下一个字符一样,就count继续自增
if(now[j-1] == now[j]){
count++;
continue;
}
//如果不一样了,就把在当前数字之前的数字个数加入结果中并且把数字也放入,最后count重新计数
else{
newstr.push_back('0' + count);
newstr.push_back(now[j-1]);
count = 1;
}
}
//处理源字符串的最后一个字符
newstr.push_back('0' + count);
newstr.push_back(now[len -1]);
dp[i] = newstr;
}
return dp[n-1];
}
};
有几个点注意:
1.就是string的加入后需字符用的是push_back。
2.对于数字转化字符处理:‘0’ + count。
3.处理好中间结果再加入最后的序列dp中去。