【发布时间】:2020-02-03 15:13:08
【问题描述】:
我正在尝试编写用于删除句子中重复单词的最佳代码(良好的运行时效率)。
例如,函数的输入字符串Jack Juliet Juliet Jill Jack Romeo Jack Jill应该返回Jack Juliet Jill Romeo
以下是我的代码:
std::string removeDuplicateWords(const std::string& str)
{
std::stringstream ss (str);
std::unordered_set<std::string> string_history;
std::string current_string, output_string;
ss >> current_string;
string_history.insert(current_string);
output_string += current_string;
while(ss >> current_string) {
if(string_history.find(current_string) == string_history.end()) {
output_string += " " + current_string;
string_history.insert(current_string);
}
}
return output_string;
}
【问题讨论】:
-
在每个插入上使用
std::move可能会很棒。您也可以将output_string更改为stringstream,然后返回output_string.str()。 -
我认为为了更好的可读性,您至少应该使用
标头。另外我建议您查看 range-v3 库。视图可以懒惰地完成它,因此您可能会获得性能提升。 -
@DeiDei 为什么将
output_string更改为stringstream?然后你将不得不复制它的缓冲区。 -
要回答此类问题,您的出发点应该是为您的程序提供您尝试优化的输入类型(例如,大量单词)并在探查器。这会告诉你时间都花在了哪里,如果那是你优化的目标!
标签: c++ c++11 optimization runtime