編者水平有限,若有不妥之處,還望留言交流,謝謝~
題目一:
描述:輸入一串隨機的數,用逗號隔開。如果有重複數字就輸出最靠後的一個,沒有重複的就輸出-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++初學者,好不容易完成了兩道題,可能第一題感覺複雜度有點高了,不過不影響求解,希望有效率更高的方法,大家交流哈。