Question:
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
My Answer:
|
|
Using StringBuilder, it’s mutable
Running time: 7ms
Better Answer:
|
|
Using char[]
Running time: 3ms, faster~
StringBuilder VS Char Array
StringBuilder
The StringBuilder class represents a mutable string of characters. StringBuilder is said to be mutable because it can be modified once it has been created by appending, removing, replacing, or inserting characters. A StringBuilder object maintains a buffer to accommodate the concatenation of new data. New data is appended to the end of the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, then the new data is appended to the new buffer.
Char Array
In some contexts using char[] arrays is far more efficient if the maximum size of the strings are known and if the string manipulation requirements are simple. Following are the remarks from the MSDN documentation about the char structure:
The .NET Framework uses the Char structure to represent a Unicode character. The Unicode Standard identifies each Unicode character with a unique 21-bit scalar number called a code point, and defines the UTF-16 encoding form that specifies how a code point is encoded into a sequence of one or more 16-bit values. Each 16-bit value ranges from hexadecimal 0x0000 through 0xFFFF and is stored in a Char structure. The value of a Char object is its 16-bit numeric (ordinal) value.