查找机器人移动方向缩减后的字符串的 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP