您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2024/11/26 22:53:20发布21次查看
在本文中,我们将讨论如何从一个只包含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 solutionwe 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 <bits/stdc++.h>using namespace std;int main () { string str = "110010"; int length = str.length(); for (int i = 1; i < length - 1; i++) { // checking the element between two zeros if ((str.at (i - 1) == '0' && str.at (i + 1) == '0')) { // deleting the element // if it is found between two 0's str.erase (i, 1); i--; if (i > 0 && str.at (i - 1) == '0') i--; // updating the length of the string after removing the element. length = str.length (); } } cout << "string after removing elements between the two zeros: " << str; return 0;}
outputstring after removing elements between the two zeros: 1100
理解代码使用循环从索引1到(长度-1)遍历字符串。检查第i个索引的前一个和后一个索引是否等于'0'。如果等于'1',则从该索引处删除该字符。使用新变量更新长度变量。最后,在循环结束后打印更新后的字符串。结论在本文中,我们讨论了从包含'0'和'1'字符的字符串中删除两个零之间的元素。我们还看到了一个解决相同问题的c++程序;我们可以使用其他语言如c、java、python等编写这个程序。希望您觉得本文有帮助。
以上就是使用c++移除两个零之间的元素的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product