LeetCode 917. Reverse Only Letters

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 '\\'.

这题是要把一个string里的所有英文字母reverse,但是不reverse别的字符。就,刚做完905觉得这题跟905其实是一模一样的,都是要判断当前字符符不符合条件,只swap符合条件的。写起代码来也一模一样,只是复习了一下判断英文字母是Characters.isLetter(),并且不能直接对s.charAt()进行赋值,只能重新建一个新的char array来return了。

class Solution {
    public String reverseOnlyLetters(String s) {
        char[] chars = s.toCharArray();
        int start = 0;
        int end = s.length() - 1;
        while (start < end) {
            if (!Character.isLetter(chars[start])) {
                start++;
            } else {
                if (Character.isLetter(chars[end])) {
                    char temp = chars[start];
                    chars[start] = chars[end];
                    chars[end] = temp;
                    start++;
                }
                end--;
            }
        }
        return new String(chars);
    }
}

你可能感兴趣的:(LeetCode,leetcode)