Description:
Given a string consists of only characters 0 and 1. You can only delete characters from it.
You want to change it into a string contains only alternating 0 and 1. Namely no Two consecutive characters are the same.
How many characters do you need to delete at least?
Input
A string consists of only characters 0 and 1 whose length is no longer than 100000.
Output
The least number of characters to delete.
Sample Input
1011
Sample Output
1
这是一个01字符串问题
只要遍历整个字符串,计算与前一个字符不同的字符个数即可。
class Solution {
public:
int leastDeletion(string &s) {
int length = s.size();
int count = 0;
char flag = s[0];
for(int i = 1; i < length; i++) {
if(s[i] == flag) {
count++;
}else {
flag = s[i];
}
}
return count;
}
};