Count and Say
https://leetcode.com/problems/count-and-say/leetcode 38
思路:
i指向字符串的第一个字母,然后用j往后移动,记录s[i]与s[j]相等的字符的个数count;把count变成相应的字符push_back到目标字符串中,把s[i]push_back到目标字符串中i指向下一个不同的字符(即当前j的值)如此循环
代码:
string countNext(
string s){
int len = s.length();
int i =
0;
string ans;
while (i<
len) {
int j=i;
int count =
0;
while (s[i]==s[j]&&j<
len) {
count++;
j++;
}
ans.push_back(count+
'0');
ans.push_back(s[i]);
i = j;
}
return ans;
}
string countAndSay(
int n) {
string ans=
"1";
for (
int i
=1; i<n; i++) {
ans = countNext(ans);
}
return ans;
}
ans.push_back(count+’0’); //注意:并不是push_back(count),因为count为int,我们需要把它变成相应的字符
转载请注明原文地址: https://ju.6miu.com/read-661802.html