用 C++,找出訊號到達字串中所有位置所用的時間


在本教程中,我們將討論一個程式,找出訊號到達字串中所有位置所用的時間

為此,我們會提供一個包含 ‘x’ 和 ‘o’ 的字串。一個訊號源自 ‘x’,並向兩個方向傳播,在單位時間內將一個 'o' 值更改為 'x'。我們的任務是計算將整個字串轉換為 'x' 需要的總時間。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
//calculating the total required time
int findMaximumDuration(string s, int n) {
   int right = 0, left = 0;
   int count = 0, maximumLength = INT_MIN;
   s = s + '1';
   for (int i = 0; i <= n; i++) {
      if (s[i] == 'o')
         count++;
      else {
         if (count > maximumLength) {
            right = 0;
            left = 0;
            if (s[i] == 'x')
               right = 1;
            if (((i - count) > 0) && (s[i - count - 1] == 'x'))
               left = 1;
            count = ceil((double)count / (right + left));
            maximumLength = max(maximumLength, count);
         }
         count = 0;
      }
   }
   return maximumLength;
}
int main() {
   string str = "xooxoooxxoooxoooxooxooox";
   int length = str.size();
   cout << findMaximumDuration(str, length);
   return 0;
}

輸出

2

更新於:2020-8-19

64 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告