Problem 279413 · medium · Phase 02 Linear Data Structures

Reverse Letters, Keep the Punctuation

strings · reversal · iteration

Write reverse_letters_in_words(s) that reverses the letters of every word while every non-letter character (spaces, digits, punctuation) stays exactly where it is. A word is a maximal run of letters, so an apostrophe or hyphen splits a word into two runs that are reversed separately.

Examples

Input:  s = "hello, world!"
Output: "olleh, dlrow!"

Input:  s = "Don't stop"
Output: "noD't pots"

Input:  s = "a-b"
Output: "a-b"

Constraints

  • 0 <= len(s) <= 10**5, printable ASCII
  • Target: O(n) time

Goals

  • Identify maximal runs of letters
  • Reverse each run in place while leaving other characters fixed
  • Flush the final run after the loop
Starting Python…