BC102 - Editorial

#PROBLEM LINK:

Practice
Contest

Author: Ayush Nagal

#DIFFICULTY:
EASY

#PREREQUISITES:
String

#PROBLEM:
Given a sentence, the task is to reverse only the first word of the given sentence, leaving rest of the sentence unchanged.

#EXPLANATION:
In order to solve the given problem, we need to find the index of the last character of the first word. Once we have the index, we can simply reverse that much part of the sentence and display it.

for(int i=0;i<l;i++)
{
   if(s[i]==' ' && f==0)
  {
      f=1;
      cout<<s1;
      printf(" ");
  }
  else if(f==0)
  s1=s[i]+s1;
  else
  printf("%c",s[i]);
}

But in case there is only one word in the given sentence the above code won’t work. We need to add the following snippet:

if(f==0)
{
   int l1=s1.length();
   for(int i=0;i<l1;i++)
   printf("%c",s1[i]);
}

#AUTHOR’S SOLUTION:
Author’s solution can be found here.

3 Likes