package com.mkyuan.leetcode.string;
/**
* @Author shuyg
* @Date 2023-04-28
**/
public class ReverseString {
public static void main(String[] args) {
char s[] = {'h', 'e', 'l', 'l', 'o'};
ReverseString reverseString = new ReverseString();
reverseString.reverseString(s);
System.out.println(s);
}
public void reverseString(char[] s) {
helper(0, s.length - 1, s);
}
//将字符数组 s 中从 start 到 end 的字符串反转
public void helper(int start, int end, char[] s) {
//start 大于等于 end,则不用再进行反转操作了,直接返回即可。
if (start >= end) {
return;
}
char tmp = s[start];
s[start] = s[end];
s[end] = tmp;
// 递归调用 helper 方法,反转 s 数组中下标从 start + 1 到 end - 1 的字符串
helper(start + 1, end - 1, s);
}
}
字符串反转
于 2023-04-28 12:45:41 首次发布