In theory, it could be done in five hours all with local trains (Ferrovie del Sud Est) changing in Maglie, Zollino, Lecce and Martina Franca. Timetable at https://www.fseonline.it/ricerca.aspx (use a near date as they show timetables only for the next week - you will have to segment the trip as Otranto-Lecce and Lecce-Alberobello). Ferrovie Sud Est runs a large network of slow and relatively infrequent commuter trains, not really geared for tourism, and both Otranto and Alberobello are on their network.
Another alternative would be Otranto-Maglie-Zollino-Lecce-Bari-Alberobello; probably it would take the same time, you would need tickets from two different railway networks (Lecce-Bari would be on Trenitalia).
Short of driving, I do not know another way to do it. BTW, I would probably drive. We are talking about using a lot of slow trains going from sleepy town to sleepy town. If you are an adventurous kind of person you may try - the worst it can happen to you is being stranded two hours in a whitewashed station building in the middle of olive orchards. You will be slowly moving between places like this where the last English speaker was seen in 20th century: http://www.yogainsalento.com/wp-content/uploads/2012/11/dove-siamo-3.jpg
If you need fast and easy service, it is not a trip for you.