首頁  >  文章  >  後端開發  >  將二進位字串中的1和0分別分隔在不同的半部中

將二進位字串中的1和0分別分隔在不同的半部中

王林
王林轉載
2023-08-27 16:45:04749瀏覽

將二進位字串中的1和0分別分隔在不同的半部中

在本教程中,我們需要將給定二進位字串的所有 1 和 0 分成兩半。在這裡,我們需要從給定的字串中取出一個子字串,並將其反轉以分隔不同部分的 0 和 1。最終,我們需要計算子字串將 1 和 0 分成兩半所需的反轉總數。

問題陳述 - 我們給出了偶數長度的二進位字串。我們需要多次從給定字串中取出任何子字串並將其反轉以將其分成兩半。我們需要在最後列印所需反轉的總數。

範例

Input –  str = 0011
Output – 0

說明

我們需要 0 次反轉,因為字串被分成兩半。

Input –  str = 0011101000
Output – 2

說明

  • 首先,從第5個索引開始取長度為2的子字串,並將其反轉。結果字串將為0011110000。

  • 之後,從開頭取一個長度為6的字串,並將其反轉。結果字串將為1111000000

Input –  str = 010101
Output – 2

說明

  • 從第一個索引開始反轉長度為 2 的字串。結果字串將為 001101。

  • 現在,反轉從第二個索引開始的長度為3的字串。最終的字串將是000111。

方法 1

此方法將計算不同相鄰元素的總數。之後,我們可以說所需的反轉總數為 count / 2。

讓我們透過調試範例輸入來理解它。

Input –  str = 00111010

所以,不同相鄰元素的總數為4。這裡,str[1] != str[2], str[4] != str[5], str[5] != str[6], str[6] != str[7]。

所以,計數值為4,答案是count/2,等於2。

演算法

  • 第 1 步 - 將「cnt」變數初始化為 0。

  • 第 2 步 - 使用 for 循環,並迭代字串。

  • 步驟 3 − 在for迴圈中,如果目前元素不等於上一個元素,則將‘cnt’變數的值增加1。

  • 步驟 4 − 如果 'cnt' 的值是奇數,則傳回 (cnt -1) /2。否則,返回 cnt/2。

Example

的中文翻譯為:

範例

#include <bits/stdc++.h>
using namespace std;
//  function to find the minimum number of reversals required to segregate 1s and 0s in a separate half
int minimumReversal(string str, int len){
   int cnt = 0; // initialize count with zero
   for (int i = 1; i < len; i++){
   
      // if the adjacent elements are not the same, then the increment count
      if (str[i] != str[i - 1]){
         cnt++;
      }
   }
   
   // For odd count
   if (cnt % 2 == 1){
      return (cnt - 1) / 2;
   }
   return cnt / 2; // For even count
}
int main(){
   string str = "00111010";
   int len = str.size();
   cout << "Minimum number of operations required is : " << minimumReversal(str, len);
   return 0;
}

輸出

Minimum number of operations required is : 2

時間複雜度 - O(N),因為我們遍歷字串。

空間複雜度 - O(N),因為我們使用常數空間來儲存計數。

在這裡,我們使用了每當找到兩個不同的相鄰元素時就需要反轉的邏輯。此外,在單一反向操作中,我們可以設定兩個元素,因此我們傳回 count/2 作為結果值。

以上是將二進位字串中的1和0分別分隔在不同的半部中的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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