欢迎来到stackoverflow。哦,算法问题?我将添加一个递归示例:
#include <iostream>
void countingThing( const std::string &input, size_t index = 1, size_t count = 1 ) {
if( input.size() == 0 ) return;
if( input[index] != input[index - 1] ) {
std::cout << input[index - 1] << " = " << count << std::endl;
count = 0;
}
if( index < input.size() ) return countingThing( input, index + 1, count + 1 );
}
int main() {
countingThing( "AAABBAABABB" );
return 0;
}
为了帮助制定算法并弄清楚要在代码中写什么,我建议几个步骤:
首先,以多种方式写出你的问题,它期望什么样的输入,以及你希望输出如何。
其次,试着在纸上解决它,逻辑是如何工作的——一个很好的提示是尝试理解你将如何解决它。你的大脑是一个很好的问题解决者,如果你能倾听它的作用,你就可以把它变成代码(虽然它并不总是最有效的)。
第三,把它写在纸上,看看你的解决方案是否符合你的预期。然后你可以将解决方案翻译成代码,确切地知道你需要写什么。