Coding Problem : 01 string(01字符串)

来源:互联网 发布:node schedule 不好使 编辑:程序博客网 时间:2024/05/16 10:42

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

题目来源:https://www.judgecode.com/problems/1001

原创粉丝点击