call(back)
Algorithms & Data StructureseasySign in to star problems

Reverse Each Alphanumeric Run

Reverse every maximal run of alphanumeric characters (A–Z, a–z, 0–9) in a string, keeping every other character where it is.

reverseRuns("ab-cd ef")       ->  "ba-dc fe"
reverseRuns("hello, world!")  ->  "olleh, dlrow!"
reverseRuns("a1b2 c3")        ->  "2b1a 3c"

Hints

Hint 1

Walk the string; when you hit an alphanumeric character, scan forward to the end of the run, reverse that slice, and continue after it.

Hint 2

In a language with mutable arrays, reverse in place with two pointers; otherwise collect pieces and join.

Asked at