g0901_1000.s0917_reverse_only_letters.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0901_1000.s0917_reverse_only_letters;
// #Easy #String #Two_Pointers #2022_03_29_Time_0_ms_(100.00%)_Space_39.9_MB_(99.08%)
/**
* 917 - Reverse Only Letters\.
*
* Easy
*
* Given a string `s`, reverse the string according to the following rules:
*
* * All the characters that are not English letters remain in the same position.
* * All the English letters (lowercase or uppercase) should be reversed.
*
* Return `s` _after reversing it_.
*
* **Example 1:**
*
* **Input:** s = "ab-cd"
*
* **Output:** "dc-ba"
*
* **Example 2:**
*
* **Input:** s = "a-bC-dEf-ghIj"
*
* **Output:** "j-Ih-gfE-dCba"
*
* **Example 3:**
*
* **Input:** s = "Test1ng-Leet=code-Q!"
*
* **Output:** "Qedo1ct-eeLg=ntse-T!"
*
* **Constraints:**
*
* * `1 <= s.length <= 100`
* * `s` consists of characters with ASCII values in the range `[33, 122]`.
* * `s` does not contain `'\"'` or `'\\'`.
**/
public class Solution {
public String reverseOnlyLetters(String s) {
char[] array = s.toCharArray();
int i = 0;
int j = array.length - 1;
while (i < j) {
if (Character.isLetter(array[i]) && Character.isLetter(array[j])) {
char temp = array[i];
array[i++] = array[j];
array[j--] = temp;
} else if (Character.isLetter(array[i])) {
j--;
} else if (Character.isLetter(array[j])) {
i++;
} else {
i++;
j--;
}
}
return new String(array);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy