Leetcode 917 仅仅反转字母

917. 仅仅反转字母

题目描述

给你一个字符串 s ,根据下述规则反转字符串:

  • 所有非英文字母保留在原有位置。
  • 所有英文字母(小写或大写)位置反转。

返回反转后的 s

示例 1:

输入:s = "ab-cd"
输出:"dc-ba"

示例 2:

输入:s = "a-bC-dEf-ghIj"
输出:"j-Ih-gfE-dCba"

示例 3:

输入:s = "Test1ng-Leet=code-Q!"
输出:"Qedo1ct-eeLg=ntse-T!"

方法:双指针

​ 整体而言,这个题目还是比较简单的,双指针的想法也比较容易想到。我们可以设置 leftright 两个指针,分别从字符串 s 的首尾开始遍历。只要 leftright 指向的是字母,且 left< right ,那我们就交换两个下标的值。

class Solution {
    public String reverseOnlyLetters(String s) {
        char[] chars = s.toCharArray();
        int left = 0, right = chars.length - 1;
        while (left < right) {
            while (left < right && !Character.isLetter(s.charAt(left))) { // 判断左边是否扫描到字母
                left++;
            }
            while (right > left && !Character.isLetter(s.charAt(right))) { // 判断右边是否扫描到字母
                right--;
            }
            if (left < right) {
                char temp = chars[left];
                chars[left] = chars[right];
                chars[right] = temp;
                ++left;
                --right;
            }
        }
        return new String(chars);
    }
}
posted @ 2022-02-23 10:09  云小杰  阅读(53)  评论(0)    收藏  举报