常に現在の文字列の先頭から位置までの部分文字列を引数として渡す関数を再帰的に呼び出します。C を使用していた場合は、ポインタを文字列の最初の位置に渡し、次に必要な長さを渡すことができます。それにもかかわらず、クラスを使用して同じ結果を達成したいと思いstring
ます。出来ますか?を使用する場合const
、コンパイラは独自に最適化を行うのに十分スマートですか? さらに良いことに、コンパイラが実際に引数のコピーを作成するか、参照を渡すかを自分で確認する方法はありますか?
私の質問は、誰かatoi
がatof
.
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#include <string>
using namespace std;
map<string, int> cache;
bool valid_character_number(string a) {
return 0 < stoi(a.substr(a.size() - 2, 2)) && stoi(a.substr(a.size() - 2, 2)) <= 26;
}
bool zero_last_digit(string a) {
return a[a.size() - 1] == '0';
}
bool zero_before_last_digit(string a) {
return a[a.size() - 2] == '0';
}
int decodings(string a) {
if (a.size() == 0)
return 1;
if (a.size() == 1) {
if (zero_last_digit(a))
return 0;
else
return 1;
}
if (cache.find(a) != cache.end())
return cache[a];
if (zero_last_digit(a) && valid_character_number(a))
return cache[a] = decodings(a.substr(0, a.size() - 2));
else if (valid_character_number(a) && !zero_before_last_digit(a))
return cache[a] = decodings(a.substr(0, a.size() - 1)) + decodings(a.substr(0, a.size() - 2));
else
return cache[a] = decodings(a.substr(0, a.size() - 1));
}
int main() {
string input;
while (true) {
cin >> input;
if (input.size() == 1 && stoi(input) == 0)
return 0;
cout << decodings(input) << endl;
}
return 0;
}