Recursively swap pairs of letters in a string in java - java

For example, if I call exchangePairs("abcdefg"), I should receive "badcfeg" in return.
This is for a homework assignment, any kind of pseudocode would be very helpful. I am just beginning to learn recursion and up until this problem I haven't had too much of an issue.

public String swapPairs(String s) {
if (s.length() < 2)
return s;
else
return swap(s.charAt(0), s.charAt(1)) + swapPairs(s.substring(2));
}

You're not just beginning to learn recursion, because recursion is part of your everyday live. You just don't notice, because it is so normal and nobody calls it recursion.
For example, you watch a movie on TV, and in one scene there is someone watching a movie on TV.
In programming, recursion is a way to make hard things easy. Always start with the easy case:
What is the result of exchangePairs("")?
What is the result of exchangePairs("x") where x is any character?
Suppose you have already completed exchangePairs(), how would the result be for "xy..." where "..." is any string? Surely "yx+++", where "+++" is the result of exchangePairs("...").
Now, it turns out that we've covered all cases! Problem solved!
Such is the greatness of recursion. You just use your function as if it were complete despite you've not completed it yet.

Why use recursion?
for (int i = 0; i + 1 < strlen(str); ++i) {
char tmp = str[i + 1];
str[i + 1] = str[i];
str[i] = tmp;
}
If you have to use recursion, I suppose you could do something like this:
char* exchangePairs(char* str) {
if (strlen(str) >= 2) {
// if there are characters left, swap the first two, then recurse
char tmp = str[1];
str[1] = str[0];
str[0] = str[1];
exchangePairs(str + 2);
}
return str;
}
That's in C, but it should give you the idea (I'm better in C and didn't want to just give you a copy/pasteable solution).

Use tail recursion
String reverse(String input)
{
if(String.length()==1)
{
return input;
}
else
{
return reverse(input,"");
}
}
String reverse(String input, String result)
{
if(input.length == 0) return result;
else return result(input.substring(1),input.charAt(0) + result);
}

Ok Here is my solution. I dont have Java at my disposal so I did it in C# which is very similar to Java so should be easy to understand/port;
public static char[] exchangePairs(char[] charArray, int current)
{
if(current >= charArray.Length - 1)
{
return charArray;
}
char nextChar = charArray[current + 1];
char currentChar = charArray[current];
charArray[current] = nextChar;
charArray[current + 1] = currentChar;
int i = current + 2;
return exchangePairs(charArray, i);
}
Call to the method:
exchangePairs("abcdefghij".ToCharArray(), 0);

public static String swapPairs(String s) {
String even = "";
String odd = "";
int length = s.length();
for (int i = 0; i <= length-2; i+=2) {
even += s.charAt(i+1) + "" + s.charAt(i);
}
if (length % 2 != 0) {
odd = even + s.charAt(length-1);
return odd;
} else {
return even;
}
}

A small adding on Steven's solution, you can use StringBuffer/StringBuilder.reverse() for reversing a string.
public String swapPairs(String s) {
if (s.length() < 2)
return s;
else {
return new StringBuffer(s.substring(0, 2)).reverse().toString() + swapPairs(s.substring(2));
}
}

I'd introduce an integer recursion control variable which is how much of the string has already been exchanged. At each level, check the control variable to see if there's more to do and, if so, exchange the next pair, increment by 2, and recurse.

Related

Super Reduced String: Problem with my code - Java

My solution for the Super Reduced String problem from HackerRank is giving me problems (https://www.hackerrank.com/challenges/reduced-string/problem). The example "baab" fails the test case, and I do not understand why. Here is my code:
String s = "baab";
for (int i = 0; i < s.length() - 1; i++) {
if (s.charAt(i) == s.charAt(i + 1)) {
s = s.substring(0, i) + s.substring(i + 2);
i = 0;
}
}
if (s.isEmpty()) {
return "Empty String";
} else {
return s;
}
The expected result is "Empty String", but the result is "bb".
Through debug statements it seems like the for loop does not run a third time in this specific scenario (once for "ba"ab, second for b"aa"b, and third for "bb"). Why?
I'll give you a few hints
One loop may not be sufficient
Keeping a certain boolean flag will help you to know when to stop looping
An algorithm isn't the only way to achieve this, you might want to explore another way of manipulating a String
One loop may be sufficient if StringBuilder is used which has method delete(int begin, int end)
Main point is to make a "step back" when duplicate characters are detected and deleted.
Example solution may look as follows:
static String reduce(String str) {
StringBuilder sb = new StringBuilder(str);
int i = 0;
while (i < sb.length()) {
int j = i + 1;
boolean found = false;
if (j < sb.length() && sb.charAt(i) == sb.charAt(j)) {
j++;
found = true;
}
if (found) {
sb.delete(i, j);
i --;
if (i < 0) {
i = 0;
}
} else {
i++;
}
}
if (sb.length() == 0) {
return "Empty String";
}
return sb.toString();
}

How to tackle the Codingbat String-2 oneTwo challenge?

Here is the problem statement:
Given a string, compute a new string by moving the first char to come after the next two chars, so "abc" yields "bca". Repeat this process for each subsequent group of 3 chars, so "abcdef" yields "bcaefd". Ignore any group of fewer than 3 chars at the end.
Here is my code:
// oneTwo("abc") → "bca"
// oneTwo("tca") → "cat"
// oneTwo("tcagdo") → "catdog"
public String oneTwo(String str) {
String x = "";
if (str.length() < 3) {
return "";
// return empty
} else if (str.length() == 3) {
String s = str.substring(1, str.length());
x = s + str.substring(0, 1); // last two + first char
} else if (str.length() > 3) {
int third = 2;
// start with the third element index of 2
for (int i = 0; i < str.length(); i++) {
if (i == third) {
// given three chars substring first char
// substring last two chars and add that to x
x += (str.substring(third - 1, third + 1) +
str.substring(third - 2, third - 2 + 1));
third += 3;
//work with this line but why??????
}
//third +=3;
// doesn't work with this line but why???????
}// end of for loop
}
return x;
// return modified string x
}
With third +=3 inside of if statement work but when I put that outside of if statement I don't get the desired output. I don't really understand why?
Hope this helps:
public String oneTwo(String str) {
String str2 = "";
for(int i=0; i<str.length()-2; i+=3) {
str2 = str2+str.substring(i+1,i+3)+str.charAt(i);
}
return str2;
}
Because putting it outside the loop will cause third to be increased far too often. After the first iteration i is 0, third is 5, next iteration yields i=1, third=8; i=2, third=11; i=3, third=14, etc. -> i will never reach third.
I would improve your code by dropping the entire if-statement, remove third all together and simply increment by 3 in the for-loop:
for( int i = 2; i < str.length(); i+=3){
x += (str.substring(third-1, third+1) +
str.substring(third-2, third-2 + 1));
}
If I am not misinterpreting your code you are missing logic for leaving the last characters alone if they are not part of group of three characters.
If you face such effects take a piece of paper and write down the values of the variables after each line of your code.
The if block creates an alternative execution path if the condition is true which is in every third loop iteration.
Anything behind the if block is executed in every loop iteration.
So when the line in question is inside the if block (before the closing brace) the value in variable third is only changed every third loop iteration.
When you move the line behind the closing brace the assignment is outside the if block and therefore executed every loop iteration.
For the comment = //work with this line but why??????
The value of "third" variable gets changed in the for loop only with i is equal to third character, otherwise the value of third will keep on increasing eg.
when i = 0, third = 2
when i = 1, third = 5
when i = 2, third = 8
so the if statement never gets triggered and hence it doesn't work. Hope this makes sense.
PS - I highly recommend using IDE debugger to understand this properly.
PS - It's better to use charAt method as compared for substring method for performance reason
public String oneTwo(String str) {
String temp = "";
String result = "";
int i = 0;
while (str.substring(i).length() >= 3) {
temp = str.substring(i, i + 3);
result += temp.substring(1) + temp.charAt(0);
i += 3;
}
return result;
}
public String oneTwo(String str) {
String str1 = "";
if(str.length()<3){
return str1;
}else if(str.length()>=3){
for(int i =0; i<str.length()-2; i=i+3){
str1 = str1 + str.substring(i+1,i+3)+ str.substring(i,i+1);
}
}
return str1;
}
public String oneTwo(String str) {
if(str.length()<3)return "";
return str.substring(1,3)+str.substring(0,1)+oneTwo(str.substring(3));
}
this is fairly simple as a recursive problem
public String oneTwo(String str) {
String newThreeChars = "";
if(str.length()<3){
return newThreeChars;
}
for(int i=0; i<str.length()/3; i+=3){
String threeChars = str.substring(i,i+3);
String redesigned = threeChars.substring(1) + threeChars.charAt(0);
newThreeChars +=redesigned;
}
return newThreeChars;
}
Another solution to look at...
public String oneTwo(String str) {
int i = 0;
String result = "";
Character tmpChar = '\0';
while(i <= str.length()-3){
tmpChar = str.charAt(i);
result = result + str.charAt(i+1) + str.charAt(i+2) + tmpChar;
tmpChar = '\0';
i = i + 3;
}
return result;
}
First, We loop through each letter of the given String just stopping shy of the last two letters because the word we are looking for is three letters long. Then, we are returning true if there is two letter "b"'s exactly one character apart.
public boolean bobThere(String str) {
for (int i = 0; i < str.length() - 2; i++) {
if (str.charAt(i) == 'b' && str.charAt(i+2) == 'b')
return true;
}
return false;
}
For string concatenation in a loop use StringBuilder:
public String oneTwo(String str) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length() - 2; i += 3) {
sb.append(str.charAt(i + 1)).append(str.charAt(i + 2)).append(str.charAt(i));
}
return sb.toString();
}

Shortest Palindrome with recursive solution issue

Debugging the following problem (a recursive solution) and confused what is the logical meaning of the for loop. If anyone have any insights, appreciated for sharing.
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.
For example:
Given "aacecaaa", return "aaacecaaa".
Given "abcd", return "dcbabcd".
int j = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == s.charAt(j)) { j += 1; }
}
if (j == s.length()) { return s; }
String suffix = s.substring(j);
return new StringBuffer(suffix).reverse().toString() + shortestPalindrome(s.substring(0, j)) + suffix;
KMP based solution,
public class Solution {
public String shortestPalindrome(String s) {
String p = new StringBuffer(s).reverse().toString();
char pp[] = p.toCharArray();
char ss[] = s.toCharArray();
int m = ss.length;
if (m == 0) return "";
// trying to find the greatest overlap of pp[] and ss[]
// using the buildLPS() method of KMP
int lps[] = buildLPS(ss);
int i=0;// points to pp[]
int len = 0; //points to ss[]
while(i<m) {
if (pp[i] == ss[len]) {
i++;
len++;
if (i == m)
break;
} else {
if (len == 0) {
i++;
} else {
len = lps[len-1];
}
}
}
// after the loop, len is the overlap of the suffix of pp and prefix of ss
return new String(pp) + s.substring(len, m);
}
int [] buildLPS(char ss[]) {
int m = ss.length;
int lps[] = new int[m];
int len = 0;
int i = 1;
lps[0] = 0;
while(i < m) {
if (ss[i] == ss[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len == 0) {
i++;
} else {
len = lps[len-1];
}
}
}
return lps;
}
}
thanks in advance,
Lin
My original comment was incorrect - as you've pointed out, in addition to using j'to check if s is a complete Palindrome, j is also used to find (intelligently guess?) the index around which to wrap + reverse the trailing characters from the longest palindrome which might exist at the beginning of the string. My understanding of the algorithm is as follows:
e.g. aacecaaa gives j = 7, resulting in
`aacecaaa` is `aacecaa` (palindrome) + `a` (suffix)
so the shortest palindrome appending to the start is:
`a` (suffix) + `aacecaa` + `a` (suffix)
Where the suffix consists of more than one character it must be reversed:
`aacecaaab` is `aacecaa` (palindrome) + `ab` (suffix)
So the solution in this case would be:
`ba` + `aacecaa` + `ab` (suffix)
In the worst case scenario j = 1 (since a will match when i=0 and j=0), e.g. abcd has no palindrome sequence in it, so the best which can be done is to wrap around the first character
dcb + a + bcd
To be honest, I'm not 100% confident that the algorithm you are debugging will work correctly in all cases but can't seem to find an a failed test case. The algorithm is certainly not intuitive.
Edit
I believe the shortest Palindrome can be derived deterministically, without the need for recursion at all - it seems that in the algorithm you are debugging, the recursion masks a side effect in the value of j. In my opinion, here's a way to determine j in a more intuitive manner:
private static String shortestPalindrome(String s) {
int j = s.length();
while (!isPalindrome(s.substring(0, j))) {
j--;
}
String suffix = s.substring(j);
// Similar to OP's original code, excluding the recursion.
return new StringBuilder(suffix).reverse()
.append(s.substring(0, j))
.append(suffix)
.toString();
}
I've pasted some test cases with an implementation of isPalindrome on Ideone here
public String shortestPalindrome(String s) {
String returnString ="";
int h = s.length()-1;
if(checkPalindrome(s))
{
return s;
}
while(h>=0)
{
returnString =returnString + s.charAt(h);
if(checkPalindrome(returnString+s))
{
return returnString+s;
}
h--;
}
return returnString+s;
}
public boolean checkPalindrome(String s)
{
int midpoint = s.length()/2;
// If the string length is odd, we do not need to check the central character
// as it is common to both
return (new StringBuilder(s.substring(0, midpoint)).reverse().toString()
.equals(s.substring(s.length() - midpoint)));
}

Returning a string minus a specific character between specific characters

I am going through the Java CodeBat exercises. Here is the one I am stuck on:
Look for patterns like "zip" and "zap" in the string -- length-3, starting with 'z' and ending with 'p'. Return a string where for all such words, the middle letter is gone, so "zipXzap" yields "zpXzp".
Here is my code:
public String zipZap(String str){
String s = ""; //Initialising return string
String diff = " " + str + " "; //Ensuring no out of bounds exceptions occur
for (int i = 1; i < diff.length()-1; i++) {
if (diff.charAt(i-1) != 'z' &&
diff.charAt(i+1) != 'p') {
s += diff.charAt(i);
}
}
return s;
}
This is successful for a few of them but not for others. It seems like the && operator is acting like a || for some of the example strings; that is to say, many of the characters I want to keep are not being kept. I'm not sure how I would go about fixing it.
A nudge in the right direction if you please! I just need a hint!
Actually it is the other way around. You should do:
if (diff.charAt(i-1) != 'z' || diff.charAt(i+1) != 'p') {
s += diff.charAt(i);
}
Which is equivalent to:
if (!(diff.charAt(i-1) == 'z' && diff.charAt(i+1) == 'p')) {
s += diff.charAt(i);
}
This sounds like the perfect use of a regular expression.
The regex "z.p" will match any three letter token starting with a z, having any character in the middle, and ending in p. If you require it to be a letter you could use "z[a-zA-Z]p" instead.
So you end up with
public String zipZap(String str) {
return str.replaceAll("z[a-zA-Z]p", "zp");
}
This passes all the tests, by the way.
You could make the argument that this question is about raw string manipulation, but I would argue that that makes this an even better lesson: applying regexes appropriately is a massively useful skill to have!
public String zipZap(String str) {
//If bigger than 3, because obviously without 3 variables we just return the string.
if (str.length() >= 3)
{
//Create a variable to return at the end.
String ret = "";
//This is a cheat I worked on to get the ending to work easier.
//I noticed that it wouldn't add at the end, so I fixed it using this cheat.
int minusAmt = 2;
//The minus amount starts with 2, but can be changed to 0 when there is no instance of z-p.
for (int i = 0; i < str.length() - minusAmt; i++)
{
//I thought this was a genius solution, so I suprised myself.
if (str.charAt(i) == 'z' && str.charAt(i+2) == 'p')
{
//Add "zp" to the return string
ret = ret + "zp";
//As long as z-p occurs, we keep the minus amount at 2.
minusAmt = 2;
//Increment to skip over z-p.
i += 2;
}
//If it isn't z-p, we do this.
else
{
//Add the character
ret = ret + str.charAt(i);
//Make the minus amount 0, so that we can get the rest of the chars.
minusAmt = 0;
}
}
//return the string.
return ret;
}
//If it was less than 3 chars, we return the string.
else
{
return str;
}
}

Whats the best way to recursively reverse a string in Java?

I have been messing around with recursion today. Often a programming technique that is not used enough.
I set out to recursively reverse a string. Here's what I came up with:
//A method to reverse a string using recursion
public String reverseString(String s){
char c = s.charAt(s.length()-1);
if(s.length() == 1) return Character.toString(c);
return c + reverseString(s.substring(0,s.length()-1));
}
My question: is there a better way in Java?
The best way is not to use recursion. These stuff are usually used to teach students the recursion concept, not actual best practices. So the way you're doing it is just fine. Just don't use recursion in Java for these kind of stuff in real world apps ;)
PS. Aside what I just said, I'd choose "" as the base case of my recursive function:
public String reverseString(String s){
if (s.length() == 0)
return s;
return reverseString(s.substring(1)) + s.charAt(0);
}
If you're going to do this, you want to operate on a character array, because a String is immutable and you're going to be copying Strings all over the place if you do it that way.
This is untested and totally stream of consciousness. It probably has an OB1 somewhere. And very not-Java.
public String reverseString(String s)
{
char[] cstr = s.getChars();
reverseCStr(cstr, 0, s.length - 1);
return new String(cstr);
}
/**
* Reverse a character array in place.
*/
private void reverseCStr(char[] a, int s, int e)
{
// This is the middle of the array; we're done.
if (e - s <= 0)
return;
char t = a[s];
a[s] = a[e];
a[e] = t;
reverseCStr(a, s + 1, e - 1);
}
You don't want to nest too deeply. Divide-and-conquer is the way to go. Also reduces total size of temporary strings and is amenable to parallelisation.
public static String reverseString(String str) {
int len = str.length();
return len<=1 ? str : (
reverseString(str.substring(len/2))+
reverseString(str.substring(0, len/2))
);
}
(Not tested - this is stackoverflow.)
String.concat instead of + would improve performance at the expense of clarity.
Edit: Just for fun, a tail-recursion friendly version of the naive algorithm.
public static String reverseString(String str) {
return reverseString("", str);
}
private static String reverseString(String reversed, String forward) {
return forward.equals("") ? reversed : (
reverseString(reversed+forward.charAt(0), forward.substring(1))
);
}
Correct handling of surrogate pairs is left to the interested reader.
here is my recursive reverse function that is working fine
public static String rev(String instr){
if(instr.length()<=1){
return instr;
} else {
return (instr.charAt(instr.length()-1)+rev(instr.substring(0,instr.length()-1)) );
}
}
Just for the heck of it, here's a tail-recursive method using StringBuilder (which is generally recommended over manipulating Strings).
public String reverseString(String s_) {
StringBuilder r = new StringBuilder();
StringBuilder s = new StringBuilder(s_);
r = reverseStringHelper(r, s);
return r.toString();
}
private StringBuilder reverseStringHelper(StringBuilder r, StringBuilder s) {
if (s.length() == 0)
return r;
else
return reverseStringHelper(r.append(s.charAt(0)), s.deleteCharAt(0));
}
Untested, I haven't dealt with Java in many years, but this should be about right.
If you're writing real code (not learning recursion), use StringBuilder's reverse() method. The Java Tutorial gives this example:
String palindrome = "Dot saw I was Tod";
StringBuilder sb = new StringBuilder(palindrome);
sb.reverse(); // reverse it
System.out.println(sb);
It depends on what you define as "better". :-) Seriously, though; your solution essentially uses the maximum depth of recursion; if stack size is of a concern for your definition of "better", then you'd be better off using something like this:
public String reverseString(String s) {
if (s.length() == 1) return s;
return reverseString(s.substring(s.length() / 2, s.length() -1) + reverseString(0, s.length() / 2);
}
This is what I've found to work and use recursive. You can pass str.length() as strLength argument
private static String reverse(String str, int strLength) {
String result = "";
if(strLength > 0)
result = str.charAt(strLength - 1) + reverse(str, strLength - 1);
return result;
}
In Java, since the String is immutable, the String concatenation would be more complex than it looks like.
For every concatenation, it creates a new string copying the contents of original String resulting in a linear complexity O(n) where n is the length of the string, so for m such operations it is O(m*n), we can say it is of quadratic complexity O(n^2).
We can use a StringBuilder which has O(1) complexity for each append. Below is the recursive program using StringBuilder. This uses only n/2 stack frames, so it has less space complexity than the normal recursive call which would be like s.charAt(s.length-1) + reverse(s.subString(0, s.length-2);
public class StringReverseRecursive {
public static void main(String[] args) {
String s = "lasrever gnirts fo noitatnemelpmi evisrucer a si sihT";
StringBuilder sb = new StringBuilder(s);
reverse(s, sb, 0, sb.length() - 1);
System.out.println(sb.toString());
}
public static void reverse(String s, StringBuilder sb, int low, int high) {
if (low > high)
return;
sb.setCharAt(low, s.charAt(high));
sb.setCharAt(high, s.charAt(low));
reverse(s, sb, ++low, --high);
}
}
That's definitely how I'd go about recursively reversing a string (although it might be nice to extend it to the case of an empty string in your condition.) I don't think there is any fundamentally better way.
EDIT: It may be more efficient to operate on a character array and pass a "cutoff" length down the chain of recursion, if you get my drift, rather than making substrings. However, this is not really worth nitpicking about, since it's not a terribly efficient technique in the first place.
You capture the basic idea, but extracting the last character doesn't improve clarity. I'd prefer the following, others might not:
public class Foo
{
public static void main(String[] argv) throws Exception
{
System.out.println(reverse("a"));
System.out.println(reverse("ab"));
System.out.println(reverse("abc"));
}
public final static String reverse(String s)
{
// oft-repeated call, so reduce clutter with var
int length = s.length();
if (length <= 1)
return s;
else
return s.substring(length - 1) + reverse(s.substring(0, length - 1));
}
}
As Mehrdad noted, it's best not to use recursion. If you do use it, though, you might as well keep both the first and last character each call, thus halving the number of recursive calls. That is,
public String reverseString(String s){
int len = s.length();
if (len <= 1) {
return s;
}
char fst = s.charAt(0);
char lst = s.charAt(len - 1);
return lst + reverseString(s.substring(1, len - 2)) + fst;
}
This also handles the case of the empty string. Perhaps passing along a StringBuilder with the appropriate capacity would speed things up even more, but that's left as an exercise to the reader ;)
You can try with an external variable, and add 1 by 1 all chars:
public static String back="";
public static String reverseString(String str){
if(str.length()==0){
return back;
}else {
back+=str.charAt(str.length()-1);
lees(str.substring(0,str.length()-1));
return back;
}
}
Here is my immutable version:
String reverse(String str) {
if(str.length()<2) return str;
return reverse(str.substring(1)) +str.charAt(0);
}
and tail recursive version:
String reverseTail(String str) {
if(str.length()<2) return str;
return str.charAt(str.length()-1)+ reverseTail(str.substring(0,str.length()-1));
In this context, this is totally unnecessary, but you can simulate recursion and avoid recursion depth issues if you make your own stack.
You can iterative implement recursion, which may be necessary when you have algorithms which are inherently recursive, but also need to run them for big problem sizes.
String recIterReverse (String word){
Stack <String> stack = new Stack <String> ();
stack.push(word);
String result = "";
while (!stack.isEmpty()){
String temp = stack.pop();
result = temp.charAt(0) + result;
if (temp.length() > 1){
stack.push(temp.substring(1));
}
}
return result;
}
function call:
//str:string to be reversed,i=0,j=str.length-1
public void reverseString(String str,int i,int j)
{
if(i==j)
{
System.out.println(str);
return;
}
char x=str.charAt(i);
str=str.replace(str.charAt(i),str.charAt(j));
str=str.replace(str.charAt(j),x);
i++;j--;
reverseString(str,i,j);
}
this method works too..
Try the following:
public class reverse2
{
public static void main(String name)
{
String revname=new StringBuffer(name).reverse().toString();
System.out.println("original string " + name + " and the reverse of it is " + revname);
}
}
public static String rev(String name){
if(name.length()>=1){
System.out.print(name.charAt(name.length()-1));
return rev(name.substring(0,name.length()-1));
}
else{
return ""+name.substring(0);
}
}
String rev="";
public String reverseString(String s){
if (s.length()==0) return "";
return rev+s.substring(s.length()-1,s.length())+reverseString(s.substring(0, s.length()-1));
}
public String reverseString (String s) {
if (s != null && s.length () > 0 ) {
rev = rev + s.substring (s.length () - 1);
reverseString (s.substring (0, s.length () - 1));
}
return rev;
}
public class StringUtility {
public static void main(String[] args) {
StringUtility stringUtility = new StringUtility();
String input = "santosh123";
int middle = input.length() / 2;
middle = middle - 1;
System.out.println(stringUtility.stringReverse(input, middle));
}
public String stringReverse(String input, int middle) {
if (middle == -1) {
System.out.println("if");
return input;
} else {
System.out.println("else");
input = swapChar(input, middle);
middle = middle - 1;
return stringReverse(input, middle);
}
}
private String swapChar(String input, int middle) {
StringBuilder str = new StringBuilder(input);
char begin = str.charAt(middle);
int endIndex = input.length() - middle - 1;
char end = str.charAt(endIndex);
str.setCharAt(middle, end);
str.setCharAt(endIndex, begin);
System.out.println(str + " " + middle + " " + endIndex);
return str.toString();
}
}
If you think less code is good then....
static String reverse(String str){
return str.length()>=2 ? str.charAt(str.length()-1) + reverse(str.substring(0,str.length()-1)) : str ;
}
There are about 20 answers already but I'll just throw in my recursive algorithm as well. It may be a little verbose but it is at least readable.
public static String reverseString(String str) {
return reverseString("", str);
}
private static String reverseString(String result, String original) {
if (original.length() == 0) {
return result;
} else {
int length = original.length();
String lastLetter = original.substring(length - 1, length);
original = original.substring(0, length - 1);
return reverseString(result + lastLetter, original);
}
}
The code basically recursively takes the end of the string and moves it in front. For example if the string we want to reverse is "jam," then each time the helper method is called, result and original strings are as follows:
// result: original:
// "" jam
// m ja
// ma j
// maj ""
Reverse String using the recursive method call.
Sample Code
public static String reverseString(String s) {
if (s.length() == 0) {
return s;
}
else {
return s.charAt(s.length() - 1) + reverseString(s.substring(0, s.length() - 1));
}
}
This is my solution,I saw in many solutions above we are getting the string length but ideally we don't need that. The Zen is to use recursion, just chop the first char of string and pass the rest to recursive method. Yay!! we got the solution.
private static void printReverse(String str) {
if (!str.isEmpty()) {
String firstChar = str.substring(0, 1); //Get first char of String
String newstr = str.substring(0, 0) + str.substring(1); // Get remaining string
printReverse(newstr); // Recursion magic
System.out.print(firstChar); //Output
}
}
public static String reverse(String s){
int n = s.length()-1;
if(n >=0)
return s.substring(s.length()-1)+ReverseString(s.substring(0,n--));
else return "";
}

Categories