From 10de7e7ec1b356815c78c4759e9cd2d8ecf98d61 Mon Sep 17 00:00:00 2001 From: 8ga Date: Fri, 10 Jan 2025 11:15:48 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=20StringReverse.java?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- StringReverse.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 StringReverse.java diff --git a/ StringReverse.java b/ StringReverse.java new file mode 100644 index 0000000..b394a67 --- /dev/null +++ b/ StringReverse.java @@ -0,0 +1,17 @@ +public class StringReverse { + // 字符串反转 数组双指针解法 + // String无法直接操作内部的char数组,避免不了2倍内存开销 + public static void main(String[] args) { + String str = "1234567"; + char[] chars = str.toCharArray(); + int len = chars.length; + char x, y; + for (int index = 0, mid = len >> 1, end = len - 1; index < mid; index++, end--) { + x = chars[index]; + y = chars[end]; + chars[index] = y; + chars[end] = x; + } + System.out.println(new String(chars)); + } +}