From 066dd615a66baea8b2c8a007d23c25377368fc05 Mon Sep 17 00:00:00 2001 From: MarcHines Date: Thu, 1 Jun 2017 08:09:19 -0400 Subject: [PATCH] Update ReverseString.java Using recursion for reversing a String serves us no benifit. It places extra load on the stack, and it is less efficient than doing so iteratively. I understand now that we can not use built in reverse function, but using recursion is still the worst way we could do the task of String reversal. Everytime we call the reverse method we are placing an extra frame on our stack. This uses space. We also create another string that we are appending our result to with the recursive solution, which is slow because under the hood, Java will create a new empty String and then append each character to the new String, one char at a time. If we do this for each character, then asymtotically we now have time complexity of O(n^2). Recursion in this case also does not make our solution "simpler" or "more elegant". We want to use recursion when it is advantageous to do so....like traversing trees --- ReverseString.java | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/ReverseString.java b/ReverseString.java index 409735502ba1..81498858c376 100644 --- a/ReverseString.java +++ b/ReverseString.java @@ -16,19 +16,17 @@ class ReverseString * @param str String to be reversed * @return Reversed string */ - static String reverseString(String str) - { - String reverse=""; - if(str.length()==1) - { - return str; - } - else - { - reverse=reverse+str.charAt(str.length()-1)+reverseString(str.substring(0,str.length()-1)); - return reverse; - } - } + public static String reverse(String str){ + if(str.isEmpty() || str == null) return str; + + char arr[] = str.toCharArray(); + for(int i = 0, j = str.length() - 1; i < j; i++, j--){ + char temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + return new String(arr); + } /** * Main Method @@ -45,4 +43,4 @@ public static void main(String args[]) throws IOException br.close(); } } - \ No newline at end of file + pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy