This will not work if the string contains an even number of duplicates of a word, or a word that is a reverse of another word in the string. Consider the input stressed desserts.
In the first iteration of the for loop, all instances of stressed will be replaced with desserts, leaving str equal to desserts desserts.
In the second iteration, all instances of desserts will be replaced with stressed, including the desserts introduced by the first iteration's replacement.
This gives the incorrect output stressed stressed.
If a word is repeated an even number of times, this solution will also reverse the reversal for that word.
This comment is hidden because it contains spoiler information about the solution
This will not work if the string contains an even number of duplicates of a word, or a word that is a reverse of another word in the string. Consider the input
stressed desserts
.In the first iteration of the
for
loop, all instances ofstressed
will be replaced withdesserts
, leavingstr
equal todesserts desserts
.In the second iteration, all instances of
desserts
will be replaced withstressed
, including thedesserts
introduced by the first iteration's replacement.This gives the incorrect output
stressed stressed
.If a word is repeated an even number of times, this solution will also reverse the reversal for that word.