- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- C++ code to count steps to reach final position by robot
- Finding the final direction of movement in JavaScript
- C++ code to find minimum correct string from given binary string
- Find the direction from given string in C++
- C++ code to find the number of dial rotations to print a string
- C++ code to find palindrome string whose substring is S
- C++ code to find string where trygub is not a substring
- Robot Return to Origin in C++
- C Program to find direction of growth of stack
- C++ Program to check string can be reduced to 2022 or not
- C++ code to count number of even substrings of numeric string
- Robot Bounded In Circle C++
- C++ program to find reduced size of the array after removal operations
- C++ code to find winner of math contest
- C++ code to find center of inner box

Advertisements