Nuggets team number online, help you Offer impromptu! Click for details
Topic describes
Reversing strings is a common basic problem, and the code is concise, often used as a hot field problem. Common topics are described as follows:
Write a function that reverses the input string. The input string is given in the form of the character array char[].
Examples are as follows:
Output: [" O "," L "," L "," E "," H "]Copy the code
Thought analysis
- String questions are the most common interview questions. In the actual investigation, we need to implement the algorithm simply and efficiently instead of directly calling the system function.
code
public class ReverseString { public static void main(String[] args) { char[] s = new char[]{'h','e','l','l','o'}; new ReverseString().reverseString(s); } public void reverseString(char[] s) { for (int i = 0, j = s.length - 1; i < j; i++, j--) { char temp = s[i]; s[i] = s[j]; s[j] = temp; }}}Copy the code
conclusion
- Method 1: If the problem asks for nothing else, we can simply create an array and return it in reverse order.
- Method two: dual-pointer solution. Double Pointers solve the inversion problem. The code above uses the beginning and end pointer traversal, and then swaps characters. No extra space is used and the time is O(n/2). More efficient!
- The head-and-tail double-pointer traversal technique is also often used in sorting arrays. In addition to the head and tail double Pointers, there are fast and slow double Pointers, is also very common skills.
- This topic is relatively simple, the code is simple, we should memorize, practice more, form muscle memory. Do difficult, complex topics for the future solid foundation.