这个题在京东c++实习岗一面的时候,面试官让我手撕的,当时思路清晰,就是不知道自己写成什么样子了,记不住了。
思路如下:用map实现,只需要遍历一次,一旦出现次数>1,立即返回。
下面要强调的是:map.insert()函数要用pair插入,并且插入时不会重复插入,也就是数,加入,key值已经存在,那么不会再更改value的值,所以需要和map.find(k)搭配使用。
也可以直接以数组的形式进行访问,这样是可以在key值相同的情况下,修改value的值。
#include <iostream>
#include <string>
#include <map>
using namespace std;
bool checkRepeated(string str);
int main()
{
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;
}