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