Javatpoint Logo
Javatpoint Logo

Reverse String with Special Characters in Java

If you're given a string that has both an alphabet (from "a" to "z" as well as "A" to "Z") as well as a special character, you need to reverse the string without changing the special character.

Example:

Input: s = "j,s$v"

Output: s = "v,s$j"

Take note that neither $ nor, are relocated.

The only reversed subsequence is "jsv."

Input: str = "Bc,d,ef!$"

Output: str = "fe,d,cB!$"

Easy Resolution:

  • Make a character array with the name temp[ ].
  • Copy alphabetical characters to temp[ ] from the provided array.
  • Apply the common string reversal method to temp[ ].
  • Now perform a single loop iteration over the input string as well as the temporary data. Replace any alphabetic characters in the input string with the current temp[ ]character.

The application of the above strategy is seen below:

File name: ReverseStringSpcl.java

Output:

The string after reversing is: eD,C,Ba!$

Time Complexity: O(N), where N is the string's length.

Space Complexity: O(N), where N represents the string's length.

Effective Approach

The above solution has an O(n) time complexity, but it uses more space and traverses the input string twice.

With just one traversal and no additional room, we can reverse. The algorithm is listed below.

The aforementioned method is implemented in the ways listed below.

File name: ReverseStringSpcl1.java

Output:

Given string is: b!!!c.d.e,f'g,hij
 The string after reversing is: j!!!i.h.g,f'e,dcb 

Time Complexity: O(N), where N is the string's length.

Space Complexity: O (1).







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA