2018北理计算机夏令营上机题和代码

                                                        编者水平有限,若有不妥之处,还望留言交流,谢谢~

题目一:

描述:输入一串随机的数,用逗号隔开。如果有重复数字就输出最靠后的一个,没有重复的就输出-1。

如输入:1,2,3,4,4,3,2,1     输出:1

   输入:1,2,3,4,5,6,7,8    输出:-1

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

//判断一串字符是否有重复数字
bool IsRepeat(string a) {
	int flag = 0;
	for (int i = 0; i < a.length(); i+=2) {
		for (int j = i + 2; j < a.length(); j += 2) {
			if (a[j] == a[i]){
				flag = 1;
				return true;
			}
		}
	}
	if (!flag) {
		return false;
	}
}

int main()
{
	string str;
	string::iterator it1;
	string::iterator it2;
	getline(cin, str);
	int temp[100];//保存重复的数字
	int i = 0;
	/*
	 *  测试输入的字符能否正确输出。
	 *  cout << str << endl;
	 */
	if (IsRepeat(str)) { //有重复数字的话继续
		//第一个迭代器从字符串右侧往回扫描
		for ( it1 = str.end()-1; it1!=str.begin(); it1 -= 2) {
			//第二个迭代器从字符串右侧扫描
			for (it2 = str.begin(); it2 != it1; it2 += 2) {
				if (*it2 == *it1) {  //发现了重复的数字,就把it1指向的数字存储
					temp[i++] = *it1 - '0';
				}
			}
		}
		cout << temp[0] << endl;//第一个找到的重复数字一定在temp的第一个位置
	}
	else { //没有重复直接输出-1
		cout << -1 << endl;
	}
	return 0;
}

题目二:

描述:一次shift操作就是把一个单词的第一个挪到最后,单词有n位就最多挪n次,问可以和原单词相同几次。

如输入:byebye    输出:2

    输入:abcd    输出:1

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

//一次挪动操作
string Fhift(string a) {
	string::iterator it=a.begin();
	a.push_back(*it);//将单词的首元素移到单词尾部
	it = a.erase(it);//删除得到的新单词的首元素
	return a;
}
//判断两个单词是否相同
bool Same(string a, string b) {
	return a == b ? true : false;
}

int main()
{
	string word1;
	string word2;
	int count = 0;
	cin >> word1;
	word2 = word1; 
	for (int i = 0; i < word2.length(); i++) {
		word1 = Fhift(word1); //得到一次移动后的新单词
		if (Same(word2, Fhift(word1))) {
			count++;
		}
	}
	cout << count << endl;
	return 0;
}

C++初学者,好不容易完成了两道题,可能第一题感觉复杂度有点高了,不过不影响求解,希望有效率更高的方法,大家交流哈。

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章