【发布时间】:2013-03-19 01:58:06
【问题描述】:
我递归调用一个函数作为参数传递一个子字符串,该子字符串总是从当前字符串的开头开始直到一个位置。如果我使用 C,我可以将指针传递给字符串的第一个位置,然后传递必要的长度。不过,我想使用string 类来实现相同的结果。是否可以?如果我使用const,编译器是否足够聪明,可以自行进行优化?更好的是,有没有办法自己检查编译器是否真的复制了参数或传递了引用?
一旦有人使用atoi而不是atof,我编写了以下代码,通过了poj上问题Alphacode的测试后,我的问题被激发了。
#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;
}
【问题讨论】:
-
我看不到您的函数修改参数的任何地方。使用
const std::string &。