检查字符串是否使用STD :: MAP包含重复

Check if a string contains duplicates using std::map

本文关键字:MAP 包含重 STD 字符串 是否 检查      更新时间:2023-10-16

i具有一个函数,该函数是否通过将每个char作为钥匙放置,使用std ::映射包含重复。无法弄清楚为什么这不起作用。

#include<iostream>
#include<map>
#include<string>
int unique_char(std::string s){
 for(int i=0 ; i < s.size(); i++ )
  {
    std::map<char,int> uniq_hash_table;
    std::pair<std::map<char,int>::iterator,bool> ret;
    ret = uniq_hash_table.insert(std::pair<char,int>(s[i],0));
    if(ret.second==false)
     {
      std::cout << "The string contains duplicates" << std::endl;
      return 1;
     }
  }
return 0;
}
int main()
{
 std::string s="abcd";
 std::string s1="aabc";
 if(unique_char(s)==0){
 std::cout << "The 1st string does not contain duplicates" << std::endl;}
 if(unique_char(s1)==0){
 std::cout << "The 2nd string does not contain duplicates" << std::endl;}
 return 0;
}

对于两个示例,程序返回"字符串不包含重复项"。

ps:我故意使用std :: map来获取o(n)解决方案。

您的解决方案不起作用,因为您的std::map<char,int>在循环的每次迭代中都重新创建。然后,在循环的每次迭代中,地图都是空的。然后,没有重复。

最好使用std::set<char>。您可以做这样的事情:

bool contains_duplicated_char(const std::string& s)
{
  std::set<char> check_uniq;
  for(unsigned long int i = 0; i < s.length(); ++i)
    if(!check_uniq.insert(s[i]).second)
      return true; // Duplicated char found
  return false; // No duplicated char found
}

然后以这种方式调用:

const std::string str = "abcdefghijklamnopb";
const bool dupl = contains_duplicated(str);

为了使您的代码更加通用(管理更多数据类型),您还可以以这种方式创建您的功能:

template <typename Type, typename IteratorType>
bool contains_duplicated(IteratorType begin, IteratorType end)
{
  std::set<Type> check_uniq;
  for(IteratorType it = begin; it != end; ++it)
    if(!check_uniq.insert(*it).second)
      return true;
  return false;
}

然后将其称为:

std::vector<std::string> vec_str;
vec_str.push_back("Foo");
vec_str.push_back("Bar");
vec_str.push_back("Baz");
vec_str.push_back("Bar");
const bool dupl = contains_duplaicated<std::string>(vec_str.begin(), vec_str.end());
//...
const std::string str = "abcdefab";
const bool dupl2 = contains_duplacated<char>(str.begin(), str.end());
//...
const std::deque<long int> x(4, 0);
x[0] = 1;
x[1] = 17;
x[2] = 31;
x[3] = 0;
const bool dupl3 = contains_duplicated<long int>(x.begin(), x.end());

它不起作用,因为uniq_hash_table是为for循环中的每个符号重新创建的。

for循环之前,尝试将其移至函数的开头:

std::map<char,int> uniq_hash_table;
for(int i=0 ; i < s.size(); i++ )
{
    // ...
}

作为您的地图定义在for循环的正文中,您在每次迭代时重新创建一个空的地图。

在循环外声明您的容器,并且''会更好。

请注意,如果您从不增加int值,则可以使用集合而不是地图。