Navigating the Loop: Advanced Tips
This approach beautifully sidesteps non-alphabetical characters. But let's talk about the "how" for a moment. To ensure accuracy, remember to iterate the reversedAlpha array independently from the loop that scans the original string.
Optional: Simplifying with .shift()
If the thought of juggling another pointer or index leaves you dizzy, here's a simpler alternative: use the .shift() method. This function efficiently grabs the left-most element in an array, essentially doing the pointer's job for you. Imagine it as having a helper who hands you each reversed "gold coin" as you walk along your original path.
Method 2: The Two-Pointer Skip Technique

Dual Pointers with a Twist
The second approach also involves using two pointers, much like our first method. However, this one comes with a twist: it skips over the non-alphabetical characters directly.
How to Skip Efficiently
Just like in a dance, when a couple realizes they are out of sync, they adjust their steps. Similarly, if either of the pointers encounters a non-alphabetical character, it simply "dances" past it, without making a swap.
By adopting this approach, you get to keep the original sequence of non-alphabetical characters intact while reversing only the alphabets. Think of it as flipping some tiles on a mosaic floor without disturbing the overall pattern.
1class Main {
2 static boolean isAlpha(char c) {
3 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
4 }
5
6 static void swap(char[] arr, int a, int b) {
7 char temp = arr[a];
8 arr[a] = arr[b];
9 arr[b] = temp;
10 }
11
12 static String reverseOnlyAlphabetical(String str) {
13 char[] result = str.toCharArray();
14 int left = 0, right = result.length - 1;
15 while (left < right) {
16 if (!isAlpha(result[left]))
17 left++;
18 else if (!isAlpha(result[right]))
19 right--;
20 else {
21 swap(result, left++, right--);
22 }
23 }
24 return new String(result);
25 }
26
27 public static void main(String[] args) {
28 System.out.println(reverseOnlyAlphabetical("sea!$hells3"));
29 }
30}