说明
算法:Reverse String
LeetCode地址:https://leetcode.com/problems/reverse-string/
题目:
Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
解题思路
字符串翻转,字符串对称处理,头尾对称位置内容互相调换即可。
时间复杂度为 O(N)。
代码实现
import java.util.Arrays;
public class ReverseString {
public void reverseString(char[] s) {
int left = 0;
int right = s.length - 1;
while (left < right) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
public static void main(String[] args) {
char[] s = {'h','e','l','l','o'};
System.out.println("Input: " + Arrays.toString(s));
new ReverseString().reverseString(s);
System.out.println("Output: " + Arrays.toString(s));
}
}
运行结果
Input: [h, e, l, l, o]
Output: [o, l, l, e, h]
代码执行效率
Runtime: 10 ms, faster than 76.17% of Java online submissions for Reverse String.
Memory Usage: 43.1 MB, less than 88.54% of Java online submissions for Reverse String.
总结
字符串逆序,数组逆序都是同一个问题。