在 C++ 中查詢給定字串的方向


假設我們有一個字串,其中僅包含 L 和 R,這分別表示左旋轉和右旋轉,我們必須找到樞軸的最終方向。這裡方向為北 (N)、東 (E)、南 (S) 和西 (W)。我們假設樞軸在指南針中指向北 (N)。

因此,如果輸入類似於“RRLRLLR”,則輸出將為 E,因為初始方向為 N,RR 將指向 S,然後 LR 將再次指向相同的 N,然後 LL 將指向先前的位置 N,然後 R 將指向 E。因此 E 是最終方向。

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

  • count := 0

  • direction := 空字串

  • 初始化 i := 0,當 i - s 的長度,更新(i 增加 1),執行:

    • 如果 s[i] 與 'L' 相同,則:

      • (count 減 1)

    • 否則

      • (count 加 1)

  • 如果 count > 0,則:

    • 如果 count mod 4 與 0 相同,則:

      • direction := "N"

    • 否則當 count mod 4 與 1 相同,則:

      • direction := "E"

    • 否則當 count mod 4 與 2 相同,則:

      • direction := "S"

    • 否則當 count mod 4 與 3 相同,則:

      • direction := "W"

  • 如果 count < 0,則:

    • 如果 count mod 4 與 0 相同,則:

      • direction := "N"

    • 否則當 count mod 4 與 -1 相同,則:

      • direction := "W"

    • 否則當 count mod 4 與 -2 相同,則:

      • direction := "S"

    • 否則當 count mod 4 與 -3 相同,則:

      • direction := "E"

  • 返回 direction

示例

讓我們看看以下實現以獲得更好的理解:

即時演示

#include<bits/stdc++.h>
using namespace std;
string get_dir(string s) {
   int count = 0;
   string direction = "";
   for (int i = 0; i < s.length(); i++){
      if (s[0] == '\n')
         return NULL;
      if (s[i] == 'L')
         count--;
      else
         count++;
   }
   if (count > 0){
      if (count % 4 == 0)
         direction = "N";
      else if (count % 4 == 1)
         direction = "E";
      else if (count % 4 == 2)
         direction = "S";
      else if (count % 4 == 3)
         direction = "W";
   }
   if (count < 0){
      if (count % 4 == 0)
         direction = "N";
      else if (count % 4 == -1)
         direction = "W";
      else if (count % 4 == -2)
         direction = "S";
      else if (count % 4 == -3)
         direction = "E";
   }
   return direction;
}
int main() {
   string s = "RRLRLLR";
   cout << (get_dir(s));
}

輸入

"RRLRLLR"

輸出

E

更新於: 2020-08-19

598 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.