Find if there are duplicate characters in a string

When I was in the C++ internship on JD.com, the interviewer asked me to tear it up by hand. At that time, my thinking was clear, but I didn’t know what I wrote, and I couldn’t remember it.

The idea is as follows: use map to implement, only need to traverse once, and return immediately once the number of occurrences > 1.

The following should be emphasized: the map.insert() function should be inserted by pair, and it will not be inserted repeatedly during insertion, that is, the number, join, and key value already exists, then the value of the value will not be changed, so it needs to be combined with map. Use with find(k).

It can also be accessed directly in the form of an array, so that the value of the value can be modified when the key value is the same.

#include <iostream>
#include <string>
#include <map>
using namespace std;
bool checkRepeated(string str);
intmain()
{
	string str;
	cin >> str;

	if (str.empty() || str.length() <= 1)
		cout << 0 << endl;
	else
	{
		cout << checkRepeated(str) << endl;;
	}
	system("pause");
    return 0;
}
bool checkRepeated(string str)
{
	map<char, int> m;
	int len = str.length();
	int cnt = 0;
	for (int i = 0; i < len; i++)
	{
		//cout << str.at(i) << endl;
		//cout << str[i] << endl;
		pair<char, int> p(str[i], 1);
		auto search = m.find(str[i]);
		if (search!=m.end()&&search->second!=0)
			//cout << search->second << endl;
			return true;
		m.insert(p);

		/*m[str[i]]++;
		if (m[str[i]] == 2)
		{
			return true;
		}*/
	}
	return false;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325483822&siteId=291194637