
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Code to Find Reduced Direction String of Robot Movement
Suppose we have a string S with n letters. The letters are either 'R' or 'U'. On a 2D plane, a robot can go right or up. When it is 'R' it moves right and when it is 'U' it moves up. However the string is too large, we want to make the string smaller. A pair like "RU" or "UR" will be replaced as diagonal move "D". We have to find the length of the final updated reduced string.
So, if the input is like S = "RUURU", then the output will be 5, because the string will be "DUD"
Steps
To solve this, we will follow these steps −
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
Example
Let us see the following implementation to get better understanding −
#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; }
Input
"RUURU"
Output
3
Advertisements