用 C++ 去除二進位制字串中子串 010 的最少步驟
問題陳述
給定一個二進位制字串,任務是計算從這個二進位制字串中去除子串 010 的最少步驟
示例
如果輸入字串為 010010,那麼需要 2 步
- 將第一個 0 轉換為 1。現在,字串變為 110010
- 將最後一個 0 轉換為 1。現在,最終字串變為 110011
演算法
1. Iterate the string from index 0 sto n-2 2. If in binary string has consecutive three characters ‘0’, ‘1’, ‘0’ then any one character can be changed Increase the loop counter by 2
示例
#include <bits/stdc++.h>
using namespace std;
int getMinSteps(string str) {
int cnt = 0;
for (int i = 0; i < str.length() - 2; ++i) {
if (str[i] == '0' && str[i + 1] == '1' && str[i+ 2] == '0') {
++cnt;
i += 2;
}
}
return cnt;
}
int main() {
string str = "010010";
cout << "Minimum required steps = " << getMinSteps(str)
<< endl;
return 0;
}當你編譯並執行上述程式時,它會生成以下輸出
輸出
Minimum required steps = 2
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP