在 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP