我正在尝试解决一项任务,但不确定我是否为其使用了合适的数据结构。我的任务是查找句子是否包含唯一字符,并因此返回 bool 值。
这是我的功能:
bool use_map(string sentence) {
map<int, string> my_map;
for (string::size_type i = 0; i <= sentence.length(); i++) {
unsigned int index = (int)sentence[i];
if (my_map.find(index) != my_map.end())
return false;
my_map[index] = sentence[i];
}
return true;
}
我只找到适合我的 map 结构。也许我错过了什么?
也许在 PHP
中使用动态数组之类的东西更好?
我正在尝试使用哈希表解决方案。
最佳答案
其他答案建议std::set
这是一个解决方案。但是,他们复制了 std::set
中的所有字符然后得到 set
的大小.你真的不需要这个,你可以避免它,使用 std::set::insert
的返回值.像这样的东西:
std::set< char > my_set;
for (std::string::size_type ii = 0; ii < sentence.size(); ++ii)
{
if( ! my_set.insert( sentence[ ii ] ).second )
{
return false;
}
}
这样你会:
- 停在第一个重复的字符上,您将不会(不必要地)复制整个字符串
- 你将避免不必要的转换为
int
在你的代码中 - 将节省内存——如果你实际上不需要你
std::map< int, std::string >::second
此外,确保您需要“计算”所有 char
s 或者您想跳过其中的一些(例如空格、逗号、问号等)
关于c++ - 哪种数据结构更适合用于查找句子是否包含唯一字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14801288/