使用C++移除两个零之间的元素

使用C++移除两个零之间的元素

在本文中,我们将讨论如何从一个只包含0和1字符的给定字符串中删除两个零之间的元素。最终的字符串不应包含任何被0包围的字符’1’。例如-

Input : string = “110010”
Output : “11000”
Explanation: 1 is found between two zeros at the 4th index.

Input : string = “0010”
Output : “000”
Explanation : 1 is found between two zeros at the 2nd index.

登录后复制

Approach to find The Solution

We can apply a simple approach, i.e., traverse the string using a loop and check the previous and next elements whether they are zeros; if yes, then that index is not zero. After that, update the variable with a new length that stores length and print that string.

Example

#include
using namespace std;

int main () {
string str = “110010”;
int length = str.length();
for (int i = 1; i 0 && str.at (i – 1) == ‘0’)
i–;

// updating the length of the string after removing the element.
length = str.length ();
}
}
cout

上一篇 在C语言中,lvalue指的是可以出现在赋值运算符的左边的表达式,它代表一个可修改的对象。rvalue则是指可以出现在赋值运算符的右边的表达式,它代表一个不可修改的值
下一篇 最大可能的平衡二进制子字符串拆分,最多花费k个