Line up in the canteen
描述
One day, there is a kind of new delicious food from one of the windows in the canteen. All students want to have a taste. Therefore, they all go to this window to line up and form a sequence. We need to simplify this sequence. For example, if a sequence is 12221133345678899, we can simplify it as 1213456789.
输入
Each test case contains a sequence. There are only numbers and letters in the sequence. The max length of the sequence is 100. The input is terminated by the end of file (EOF).
输出
For each test case, you must print the simplyfied sequence in one line.
输入样例 1
12221133345678899 aabbccddeeffgg
输出样例 1
1213456789 abcdefg
实现代码(双指针算法)
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s;
while (cin >> s) {
int i = 0;
int count = 0;//记录俩字母相同的次数,因为只能保留一份
for (int j = 1; j < s.length(); j++) {
if (s[i] != s[j]) {//如果快慢指针指向的值不等,将j指向的值赋值给i+1指向的值,j再后移
i++;
s[i] = s[j];
}
else count++;//如果俩快慢指针指向相同的值,则快指针后移
}
for (int i = 0; i < s.length()-count; i++) {
cout << s[i];
}
cout << endl;
}
return 0;
}