Reversing Letters in a String with Java Solution

🚀 Day 39 of #100DaysOfCode – LeetCode Problem #917: Reverse Only Letters 💡 Problem Summary: Given a string s, reverse only the English letters while keeping all non-letter characters in their original positions. 📘 Examples: Input: s = "ab-cd" Output: "dc-ba" Input: s = "a-bC-dEf-ghIj" Output: "j-Ih-gfE-dCba" Input: s = "Test1ng-Leet=code-Q!" Output: "Qedo1ct-eeLg=ntse-T!" 🧠 Approach: Use two pointers: one starting from the beginning and one from the end. Move both pointers until they point to letters. Swap the letters and move inward. Skip over non-letter characters. 💻 Java Solution: class Solution { public String reverseOnlyLetters(String s) { char[] res = s.toCharArray(); int left = 0, right = res.length - 1; while (left < right) { if (!Character.isLetter(res[left])) { left++; } else if (!Character.isLetter(res[right])) { right--; } else { char temp = res[left]; res[left] = res[right]; res[right] = temp; left++; right--; } } return new String(res); } } ⚙️ Complexity: Time: O(n) Space: O(n) ✅ Result: Accepted (Runtime: 0 ms) 🎯 Key Takeaway: This problem highlights precision and attention to detail — even simple string manipulations can teach valuable lessons about pointer logic and conditional handling.

To view or add a comment, sign in

Explore content categories