JavaInterview JavaInterview
首页
指南
分类
标签
归档
  • CSDN (opens new window)
  • 文档集合 (opens new window)
  • 系统架构 (opens new window)
  • 微信号 (opens new window)
  • 公众号 (opens new window)

『Java面试+Java学习』
首页
指南
分类
标签
归档
  • CSDN (opens new window)
  • 文档集合 (opens new window)
  • 系统架构 (opens new window)
  • 微信号 (opens new window)
  • 公众号 (opens new window)
  • 指南
  • 简历

  • Java

  • 面试

  • 算法

  • algorithm
  • leetcode
JavaInterview.cn
2022-10-29
目录

仅仅反转字母Java

文章发布较早,内容可能过时,阅读注意甄别。

# 题目

给你一个字符串 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!"

提示

  • 1 <= s.length <= 100
  • s 仅由 ASCII 值在范围 [33, 122] 的字符组成
  • s 不含 '"' 或 '\'

# 思路

// 头尾双指针

// ♻️ 循环结束条件 (头 >= 尾)
// 头元素不是字母 (头指针++)
// 尾元素不是字母 (尾指针--)
// 头尾元素都是字母 (头++ 尾--)

# 解法


class Solution {
    // 头尾双指针

    // ♻️ 循环结束条件 (头 >= 尾)
    // 头元素不是字母 (头指针++)
    // 尾元素不是字母 (尾指针--)
    // 头尾元素都是字母 (头++ 尾--)
    public String reverseOnlyLetters(String s) {
        char[] chars = s.toCharArray();
        int sIndex = 0, eIndex = chars.length - 1;
        while (sIndex < eIndex) {
            if (!Character.isLetter(chars[sIndex])) {
                sIndex++;
            }
            if (!Character.isLetter(chars[eIndex])) {
                eIndex--;
            }
            if (Character.isLetter(chars[sIndex]) &&
                    Character.isLetter(chars[eIndex])) {
                char temp = chars[sIndex];
                chars[sIndex] = chars[eIndex];
                chars[eIndex] = temp;
                sIndex++;
                eIndex--;
            }
        }
        return new String(chars);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

# 总结

  • 分析出几种情况,然后分别对各个情况实现
微信 支付宝
最近更新
01
1686. 石子游戏VI Java
08-18
02
1688. 比赛中的配对次数 Java
08-18
03
1687. 从仓库到码头运输箱子 Java
08-18
更多文章>
Theme by Vdoing | Copyright © 2019-2025 JavaInterview.cn
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式