zoukankan      html  css  js  c++  java
  • [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 '\'.

    仅仅反转字母。

    给定一个字符串 S,返回 “反转后的” 字符串,其中不是字母的字符都保留在原地,而所有字母的位置发生反转。

    思路是逼近型的双指针。我们从 input 字符串的两侧往中间扫描,遇到不是字母的就跳过,遇到两边都是字母的才做交换的操作。

    时间O(n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public String reverseOnlyLetters(String s) {
     3         StringBuilder sb = new StringBuilder(s);
     4         int i = 0;
     5         int j = s.length() - 1;
     6         while (i < j) {
     7             if (!Character.isLetter(sb.charAt(i))) {
     8                 i++;
     9             } else if (!Character.isLetter(sb.charAt(j))) {
    10                 j--;
    11             } else {
    12                 char temp = sb.charAt(i);
    13                 sb.setCharAt(i, sb.charAt(j));
    14                 sb.setCharAt(j, temp);
    15                 i++;
    16                 j--;
    17             }
    18         }
    19         return sb.toString();
    20     }
    21 }

    LeetCode 题目总结

  • 相关阅读:
    springboot整合springmvc应用
    spring注解使用
    亨元模式 四大引用 逃逸引用 池化思想
    springboot整合连接池
    springboot整合mybatis(待更新)
    php安装imagick扩展
    js复制功能代码
    PHP7兼容mysql_connect的方法
    linux开机启动
    centos8安装php扩展memcached报错
  • 原文地址:https://www.cnblogs.com/cnoodle/p/15302817.html
Copyright © 2011-2022 走看看