Skip to content

Commit 6bc4f91

Browse files
Merge pull request TheAlgorithms#55 from MarcHines/patch-4
Update ReverseString.java
2 parents 6ff4a1f + 066dd61 commit 6bc4f91

File tree

1 file changed

+12
-14
lines changed

1 file changed

+12
-14
lines changed

ReverseString.java

+12-14
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,17 @@ class ReverseString
1616
* @param str String to be reversed
1717
* @return Reversed string
1818
*/
19-
static String reverseString(String str)
20-
{
21-
String reverse="";
22-
if(str.length()==1)
23-
{
24-
return str;
25-
}
26-
else
27-
{
28-
reverse=reverse+str.charAt(str.length()-1)+reverseString(str.substring(0,str.length()-1));
29-
return reverse;
30-
}
31-
}
19+
public static String reverse(String str){
20+
if(str.isEmpty() || str == null) return str;
21+
22+
char arr[] = str.toCharArray();
23+
for(int i = 0, j = str.length() - 1; i < j; i++, j--){
24+
char temp = arr[i];
25+
arr[i] = arr[j];
26+
arr[j] = temp;
27+
}
28+
return new String(arr);
29+
}
3230

3331
/**
3432
* Main Method
@@ -45,4 +43,4 @@ public static void main(String args[]) throws IOException
4543
br.close();
4644
}
4745
}
48-
46+

0 commit comments

Comments
 (0)