From 1c8a9c92601123ab6a1f97a43590ecabee00bb82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=B1=E6=96=87=E8=B5=B5?= <1392936858@qq.com> Date: Thu, 27 Jun 2019 00:03:16 +0800 Subject: [PATCH] =?UTF-8?q?=E9=80=92=E5=BD=92=E7=9A=84=E8=B0=83=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../leetcode/recursive/PrintReverse.java | 50 +++++++++++++++++-- 1 file changed, 47 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/ximo/datastructuresinaction/leetcode/recursive/PrintReverse.java b/src/main/java/com/ximo/datastructuresinaction/leetcode/recursive/PrintReverse.java index e9e25eb..256589a 100644 --- a/src/main/java/com/ximo/datastructuresinaction/leetcode/recursive/PrintReverse.java +++ b/src/main/java/com/ximo/datastructuresinaction/leetcode/recursive/PrintReverse.java @@ -1,5 +1,9 @@ package com.ximo.datastructuresinaction.leetcode.recursive; +import java.util.Arrays; +import java.util.StringJoiner; +import java.util.stream.Stream; + /** * @author xikl * @date 2019/6/26 @@ -13,18 +17,58 @@ public static void printReverse(char[] strArray) { /** * 递归调用 * - * @param index 索引 + * @param index 索引 * @param strArray 原始数组 */ private static void printReverse(int index, char[] strArray) { - if (strArray == null || index > strArray.length) { + if (strArray == null || index > strArray.length - 1) { return; } // 我们假设先执行后面的 printReverse(index + 1, strArray); // 然后再执行自己 - System.out.println(strArray[index]); + System.out.print(strArray[index]); + } + + public static void main(String[] args) { + char[] s = {'h', 'e', 'l', 'l', 'o'}; +// char[] s = {'h', 'e'}; +// printReverse(s); + printReverse2(s); + } + + /** + * StringJoiner的添加 + * + * @param strArray + */ + private static void printReverse2(char[] strArray) { + StringJoiner stringJoiner = new StringJoiner(",", "[", "]"); + reverse(0, strArray, stringJoiner); + System.out.println(stringJoiner.toString()); + } + + private static void reverse(int index, char[] strArray, StringJoiner stringJoiner) { + if (strArray == null || index > strArray.length - 1) { + return; + } + + reverse(index + 1, strArray, stringJoiner); + stringJoiner.add("\"" + strArray[index] + "\""); + } + + + + + + public void reverseString(char[] s) { + + for (int i = 0, j = s.length - 1; i < s.length / 2; ) { + char temp = s[i]; + s[i++] = s[j]; + s[j--] = temp; + } }