从C ++中的给定字符串中找到方向
假设我们有一个仅包含L和R的字符串,分别表示向左旋转和向右旋转,我们必须找到枢轴的最终方向。这里的方向是北(N),东(E),南(S)和西(W)。我们假设枢轴在指南针中指向北(N)。
因此,如果输入类似于“RRLRLLR”,则输出将为E,初始方向为N,RR将指向S,然后LR将再次指向相同的N,然后LL将指向先前的位置N,然后R将指向E。因此E是最终的。
为了解决这个问题,我们将遵循以下步骤-
计数:=0
方向:=空白字符串
对于初始化i:=0,当i-s的长度时,更新(将i增加1),执行-
(增加1)
(将计数减少1)
如果s[i]与'L'相同,则-
除此以外
如果count>0,则-
方向:=“W”
方向:=“S”
方向:=“E”
方向:=“N”
如果countmod4与0相同,则-
否则,当countmod4与1相同时,则-
否则,当countmod4与2相同时,则-
否则,当countmod4与3相同时,则-
如果count<0,则-
方向:=“E”
方向:=“S”
方向:=“W”
方向:=“N”
如果countmod4与0相同,则-
否则,当countmod4与-1相同时,则-
否则,当countmod4与-2相同时,则-
反之,当countmod4与-3相同时,则-
返回方向
例
让我们看下面的实现以更好地理解-
#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