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

2023年 8月 29日 61.1k 0

使用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

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论