Monday, 10 July 2017

String Character Shift

  • Given a string S of length N, shift each character of the string by K positions to the right, where KN.
For example: Say S = "hacker" and K=2. Here N=6.
Shifting each character in S by 2 positions to the right would result into erhack.
Note that S[0] i.e. 'h' is moved by 2 positions to the S[2]. Also, S[5] i.e. 'r', which is the last character in S comes round-about back to S[1] as there is no space for 'r' to go beyond the limits of string length.
Approach:
  • Declare another auxillary string shiftedS that is of the same size as S.
  • Copy ith element of S to the (K+i)th position in shiftedS. This means, shiftedS[i+K]=S[i] where 0i<N.
  • Make sure that i+K never exceeds N, because that will try to access a memory location which is not declared in shiftedS. There's a simple trick to ensure that - use (i+K)modN .

#include <iostream>
#include<string>
using namespace std;

int main()
{
    string s,p;
    cin>>s;
    int k;
    cin>>k;
    for(int i=0;i<s.size();i++)
    {
        int index=(i+k)%s.size();
        p[index]=s[i];
        
    }
  for(int i=0;i<s.size();i++) { cout<<p[i];}

    

No comments:

Post a Comment

Dynamic programming problem

Given a binary matrix, find out the maximum size square sub-matrix with all 1s. For example, consider the below binary matrix. Please...