在本文中,我们将讨论如何从一个只包含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