1. 题目链接
Musical Puzzle
2. 题目代码
正确代码
#include<iostream>
#include<vector>
#include<set>
using namespace std;
int main(){
int testCase;
cin >> testCase;
int lengthOfMelody;
string melody;
set<string> twoNote;
string note;
while(testCase --){
cin >> lengthOfMelody;
cin >> melody;
for(int subscript = 0; subscript < lengthOfMelody; subscript ++){
note += melody[subscript];
if(note.length() == 2){
twoNote.insert(note);
note = "";
note += melody[subscript];
}
}
cout << twoNote.size() << endl;
twoNote.clear();
note = "";
}
return 0;
}
问题代码(包含代码调试部分,可忽略)
#include<iostream>
#include<vector>
#include<set>
using namespace std;
int main(){
int testCase;
cin >> testCase;
int lengthOfMelody;
string melody;
set<string> twoNote;
string note;
while(testCase --){
cin >> lengthOfMelody;
cin >> melody;
for(int subscript = 0; subscript < lengthOfMelody; subscript ++){
note += melody[subscript];
if(note.length() == 2){
twoNote.insert(note);
cout << "note=" << note << endl;
note = "";
note += melody[subscript];
}
}
cout << twoNote.size() << endl;
twoNote.clear();
note = "";
cout << "check=" << twoNote.size() << endl;
}
return 0;
}
3. 题目总结
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/80ac245bc02243e88d10f59161c5e50e.png#pic_center)
① 这个题目我解了将近96分钟。中间洋洋洒洒写了那么多,后来发现有没有都一样🤣
② 上述问题代码只记录了我中后阶段的解题思路,最初的思路错的太离谱了,我在写的过程就删掉了。正确代码for循环里的note += melody[subscript];也是在调试过程中发现问题后加上去的(可以用7 abcdefg这个样例检测该行代码的作用)。
③ 一开始我采用的是vector容器,并且引入变量miniNumber记录输出结果,但是我后来发现这种方式无法排除重复短字符串的情况,因此我后来改成了set容器。
④ note += melody[subscript]; note += melody[subscript + 1]; 并不等同于
note = melody[subscript] + melody[subscript + 1]; 后者会得到空字符串
⑤ 看了一眼题解,发现我好像把这个题想复杂了。其实就是按顺序将字符串两两一组,输出组中字符串不同的小组个数