Leetcode 917. Reverse Only Letters
You are given a string s
which consists of lowercase and uppercase letters. Reverse only the letters and leave all other characters at their original positions.
Example 1:
Example 2:
Example 3:
Constraints:
1 <= s.length <= 100
s
consists of characters with ASCII values in the range [33, 122]
.s
consists of various characters, not limited to letters.public class ReverseOnlyLetters {
public String reverseOnlyLetters(String s) {
char[] arr = s.toCharArray();
int left = 0;
int right = arr.length - 1;
while (left < right) {
if (!Character.isLetter(arr[left])) {
left++;
} else if (!Character.isLetter(arr[right])) {
right--;
} else {
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
return new String(arr);
}
public static void main(String[] args) {
ReverseOnlyLetters solution = new ReverseOnlyLetters();
System.out.println(solution.reverseOnlyLetters("ab-cd")); // "dc-ba"
System.out.println(solution.reverseOnlyLetters("a-bC-dEf-ghIj")); // "j-Ih-gfE-dCba"
System.out.println(solution.reverseOnlyLetters("Test1ng-Leet=code-Q!")); // "Qedo1ct-eeLg=ntse-T!"
}
}
This approach is efficient and fulfills the problem’s requirements effectively.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?