From 4af9d61650c3cce14052231b973bf1729e69bf70 Mon Sep 17 00:00:00 2001 From: Gautamali Date: Sun, 22 Oct 2023 14:07:18 +0530 Subject: [PATCH] Implement a method to reverse strings using a two-pointer approach --- JAVA/reverseString.java | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 JAVA/reverseString.java diff --git a/JAVA/reverseString.java b/JAVA/reverseString.java new file mode 100644 index 0000000..72a3c2f --- /dev/null +++ b/JAVA/reverseString.java @@ -0,0 +1,27 @@ +public class reverseString { + public static String reverse(String str) { + // converting str to char array for easy traversal + char[] chars = str.toCharArray(); + //pointing one pointer to left + int left = 0; + //pointing another pointer to right + int right = chars.length - 1; + // moving till left and right not crosses each other + while (left < right) { + // swaping of left and right to reverse a string + char temp = chars[left]; + chars[left] = chars[right]; + chars[right] = temp; + left++; + right--; + } + + return new String(chars); + } + public static void main(String args[]){ + String str="Hacktoberfest"; + //calling the function which will return a string so we are printing that + System.out.println(reverse(str)); + } + +}