【HihoCoder - 1850】字母去重 (字串,思維)
阿新 • • 發佈:2018-11-22
題幹:
給定一個字串S,每次操作你可以將其中任意一個字元修改成其他任意字元。
請你計算最少需要多少次操作,才能使得S中不存在兩個相鄰的相同字元。
Input
只包含小寫字母的字串S。
1 ≤ |S| ≤ 100000
Output
一個整數代表答案
Sample Input
aab
Sample Output
1
解題報告:
考慮對於s[i]字元,如果改變,則會影響到s[i-1] 和 s[i+1],所以我們考慮aab和aaa的情況。不難發現我們改變中間那個字元為任意值就可以了。。。
AC程式碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define ll long long #define pb push_back #define pm make_pair #define fi first #define se second using namespace std; const int MAX = 2e5 + 5; char s[MAX]; int main() { int ans = 0; cin>>s; int len = strlen(s); for(int i = 0; i<len; i++) { if(s[i] == s[i+1]) { s[i+1] ='@';ans++; } } printf("%d\n",ans); return 0 ; }