宝石与石头——leetcode771

leetcode771——字符串比较问题,宝石与石头

#include
#include
#include
using namespace std;

int main(){
	string J;//代表石头中宝石的类型
	string S;//代表拥有的石头,其中每个char代表了一种拥有的石头类型
	//需求:算出石头中有多少是宝石
	//注意:J中字母不重复,J/S中所有字符都是字母,区分大小写,A与a不同
	//本质:找两字符串中相同字符的数量

	//思路:每次取J中一个字符,然后将S中相同字符全部删掉,最后用S的前后length做差

	/*语法知识:
	String.erase
	String.find
	remove
	remove_if

	*/
	cout << "输入宝石字符串" << endl;
	cin >> J;
	cout << "输入拥有的石头字符串" << endl;
	cin >> S;
	int n1 = J.length();
	int n2 = S.length();
	int i, j,k=0;
	char c1;
	string::iterator it;
	for (i = 0; i <= (n1 - 1); i++){
		c1 = J.at(i);
		for (j = (S.length()-1); j >=0; j--){
			it = S.begin() + j;
			if (S.at(j) == c1){
				S.erase(it); //删除字符串S中与c1相同的字符
				k++;
			}
		}
	}

	cout << k << endl;

	system("pause");
	return 0;
}

你可能感兴趣的:(算法练习,C++学习)