算法练习题,删除字符序列中重复的元素,只保留一个

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值