您的位置:首页 > 其它

对于一个字符串,请设计一个高效算法,找到第一次重复出现的字符。 给定一个字符串(不一定全为字母)A及它的长度n。请返回第一个重复出现的字符。保证字符串中有重复字符,字符串的长度小于等于500。

2017-02-24 13:58 851 查看
// 第一种方法

// ConsoleApplication10.cpp : 定义控制台应用程序的入口点。

//

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class FirstRepeat {
public:
char findFirstRepeat(string A, int n) {
// write code here
vector<char> cVec;
bool re = false;
char ch='a';
for (int i = 0;i < A.size();i++)
{
for (int j = 0;j < cVec.size();++j)
{
if (A[i] == cVec[j])
{
re = true;
ch = A[i];
break;
}
}
if (re == false)
{
cVec.push_back(A[i]);
}
else
{
break;
}

}
return ch;
}
};
int main()
{
string str = "qywyer23tdd";
FirstRepeat fr;
cout << fr.findFirstRepeat(str,str.size())<< endl;

return 0;
};

//第二种方法

// ConsoleApplication10.cpp : 定义控制台应用程序的入口点。

//

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class FirstRepeat {
public:
char findFirstRepeat(string A, int n) {
// write code here
vector <int> cVec;
char ch;
for (int i = 0;i < 128;i++)//建立一个存储字符的数组;共有128个字符
{
cVec.push_back(0);
}

for (int i = 0;i < n;i++)
{
int num = A[i];

cVec[num]= cVec[num]++;
cout << "char:" << A[i]  <<"   num:"<< cVec[num] << endl;
if (cVec[num] == 2)
{
ch= A[i] ;

break;
}

}
return ch;
}
};
int main()
{

string str = "kdbaaak";
FirstRepeat fr;
cout << fr.findFirstRepeat(str,str.size())<< endl;

return 0;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐