首頁  >  文章  >  後端開發  >  使用C++移除兩個零之間的元素

使用C++移除兩個零之間的元素

WBOY
WBOY轉載
2023-08-29 09:53:051258瀏覽

使用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, previous and next elements whether they are zeros; if yes, previous and next elements whether they are zeros; if yes, previous and next elements whether they are zeros; if yes, previous and next elements whether they are zeros; if yes, previous and next elements whether they are zeros; if yes, previous and next elements whether they are zeros; if yes, previous and next elements whether they are zeros; 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) == &#39;0&#39; && str.at (i + 1) == &#39;0&#39;)) {
         // deleting the element
         // if it is found between two 0&#39;s
         str.erase (i, 1);

         i--;
         if (i > 0 && str.at (i - 1) == &#39;0&#39;)
            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;
}

Output

String after removing elements between the two zeros: 1100
## 理解程式碼

    #使用循環從索引1到(長度-1)遍歷字串。
  • 檢查第i個索引的前一個和後一個索引是否等於'0'。
  • 如果等於'1',則從該索引處刪除該字元。
  • 使用新變數更新長度變數。
  • 最後,在循環結束後列印更新後的字串。
結論

在本文中,我們討論了從包含'0'和'1'字元的字串中刪除兩個零之間的元素。我們也看到了一個解決相同問題的C 程式;我們可以使用其他語言如C、Java、Python等來編寫這個程式。希望您覺得本文有幫助。

以上是使用C++移除兩個零之間的元素的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除