对于一个字符串,请设计一个高效算法,找到第一次重复出现的字符。
给定一个字符串(不一定全为字母)A及它的长度n。请返回第一个重复出现的字符。保证字符串中有重复字符,字符串的长度小于等于500。
测试样例:
“qywyer23tdd”,11
返回:y
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class FirstRepeat {
public:
char findFirstRepeat(string A, int n) {
char temp[500] = {0};
char dst;
for(int i=0; i < n; ++i)
{
int num = (int)A[i];
if(temp[num] == 0)
{
temp[num] = num;
}
else
{
dst = temp[num];
break;
}
}
return dst;
}
};
int main()
{
FirstRepeat s;
string A;
cin>>A;
char a =s.findFirstRepeat(A,A.length());
cout << a;
}