對於一個字符串,請設計一個高效算法,找到第一次重復出現的字符。 給定一個字符串(不一定全為字母)A及它的長度n。請返回第一個重復出現的字符。保證字符串中有重復字符,字符串的長度小於等於500。


// 第一種方法
// 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;
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM