查詢機器人移動方向縮減後的字串的 C++ 程式碼


假設我們有一個包含 n 個字母的字串 S。這些字母要麼是“R”,要麼是“U”。在二維平面上,機器人可以向右或向上移動。當為“R”時,它向右移動,當為“U”時,它向上移動。然而,字串太大,我們希望讓字串更小。如“RU”或“UR”這樣的對將被替換為對角線移動“D”。我們必須找到最終更新的縮減字串的長度。

因此,如果輸入類似於 S = "RUURU",則輸出將為 5,因為該字串將為“DUD”

步驟

要解決這個問題,我們將遵循以下步驟:

ans := 0
n := size of S
for initialize i := 0, when i < n, update (increase i by 1), do:
   if S[i] is not equal to S[i + 1], then:
      (increase i by 1)
   (increase ans by 1)
return ans

示例

讓我們看看以下實現以更好地理解:

#include <bits/stdc++.h>
using namespace std;
int solve(string S){
   int ans = 0;
   int n = S.size();
   for (int i = 0; i < n; ++i){
      if (S[i] != S[i + 1])
         i++;
      ans++;
   }
   return ans;
}
int main(){
   string S = "RUURU";
   cout << solve(S) << endl;
}

輸入

"RUURU"

輸出

3

更新日期: 2022-03-29

196 次瀏覽

職業生涯開啟您的

透過完成課程,獲得證書

開始
廣告