Popular Posts

Thursday, July 21, 2011

Reverse a line word by word AND swap two words in a given sentence

ex - my name is john
Then after reversing it will be like - john is name my


Method 1:
1. First scan the input string till midway and swap the first character with last and second character with second last and so on.
2. Second scan, swap the word within string the same way.


Problem II:
Swap two words in a given sentence
ex: my name is Khan in school.
swap name and in in the above sentence.
o/p : my in is name school.
Solution : 
Reverse the entire string  from starting word to ending word : Here starting word is name and ending word is in.So reverse the string from name to in using inplace string reversal algo.It requires O(n) traversal.
Step 1: 
Str = my name is Khan in school.
Str = my ni nahK si eman school
Step 2:
Now reverse the first word of the modifies string:
Str = my ni nahK si eman school
Str = my in nahk si eman school
Step 3 :
Now reverse the string after first word to second modified word.
Str = my in nahk si eman school
Str = my in is Khan eman school(after reversal)
Step 4 :
Now reverse the second word
Str = my in is Khan school
Str= my in is Khan name school

Original sentence         : my name is Khan in school.
After final modification : my in is Khan name school
Got the desired output.in and name are swapped in the given sentence.

No comments:

Post a Comment