在本文中,我们将讨论如何从一个只包含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 (); } } coutOutput
String after removing elements between the two zeros: 1100登录后复制
理解代码
使用循环从索引1到(长度-1)遍历字符串。检查第i个索引的前一个和后一个索引是否等于'0'。如果等于'1',则从该索引处删除该字符。使用新变量更新长度变量。最后,在循环结束后打印更新后的字符串。
结论
在本文中,我们讨论了从包含'0'和'1'字符的字符串中删除两个零之间的元素。我们还看到了一个解决相同问题的C++程序;我们可以使用其他语言如C、Java、Python等编写这个程序。希望您觉得本文有帮助。
以上就是使用C++移除两个零之间的元素的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2585376.html