Building a new string
Build a reversed copy of a string, one character at a time. About 7 minutes.
A string can't be edited, only rebuilt
In Python, Java and JavaScript, once a string is made it can't be changed, like text printed on a page. You can't swap its first letter for another. To "change" a string, you build a new one with the characters you want.
So reversing a string means walking it from the back and building a fresh string as you go.
- parts
- [d]
Start at the last index. Collect 'd' in a list; we won't glue strings together yet.
Collect the pieces, glue once
Gluing one character at a time onto a growing string can secretly copy the whole thing on every step. For a long string that gets slow.
The usual fix: collect the characters in a list (Python, JavaScript) or a StringBuilder (Java), and turn them into a string once at the very end. In C++, strings can grow cheaply, so adding one character at a time is fine.
parts = []
for i in range(len(s) - 1, -1, -1):
parts.append(s[i])
return "".join(parts)A loop walks "abc" from the last character to the first, collecting each one. What does it build?
- A"cba"
- B"abc"
- CAn error
Show the answer
"cba". The last character comes first: c, then b, then a.
Reverse a string
Return a new string with the characters of s in reverse order.
s = "stressed" → "desserts"
0 ≤ length of s ≤ 10,000 · s has letters, digits and spaces