使用 C++ 删除两个零之间的元素
在这篇文章中,我们将讨论如何从给定的只包含零和一字符的字符串中删除两个零之间的元素。最终字符串不应包含任何被零包围的“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.
寻找解决方案的方法
我们可以采用一种简单的方法,即使用循环遍历字符串,并检查前一个和下一个元素是否为零;如果是,则该索引不为零。之后,使用存储长度的新变量更新长度,并打印该字符串。
示例
#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;
}输出
String after removing elements between the two zeros: 1100
理解代码
- 使用循环遍历从索引 1 到 (长度 - 1) 的字符串。
- 检查第 i 个索引的前一个和下一个索引是否等于“0”。
- 如果它是“1”,则从该索引中删除该字符。
- 使用新变量更新长度变量。
- 最后在循环结束后打印更新后的字符串。
结论
在这篇文章中,我们讨论了从包含“0”和“1”字符的字符串中删除两个零之间的元素。我们还看到了一个 C++ 程序来解决这个问题;我们可以用其他任何语言(如 C、Java、Python 等)编写此程序。希望本文对您有所帮助。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP