首页 > 其他分享 >leetcode-917-easy

leetcode-917-easy

时间:2022-11-29 21:58:14浏览次数:44  
标签:String chars Example while easy Output Input 917 leetcode

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

思路一:双指针,先定位两个指针的位置,然后交换合法的字符

public String reverseOnlyLetters(String s) {
    char[] chars = s.toCharArray();

    int i = 0;
    int j = chars.length - 1;

    while (true) {
        while (i < chars.length && !Character.isLetter(chars[i])) {
            i++;
        }
        while (j >= 0 && !Character.isLetter(chars[j])) {
            j--;
        }

        if (i < j) {
            char t = chars[i];
            chars[i] = chars[j];
            chars[j] = t;
        } else {
            break;
        }
        i++;
        j--;
    }

    return new String(chars);
}

标签:String,chars,Example,while,easy,Output,Input,917,leetcode
From: https://www.cnblogs.com/iyiluo/p/16936835.html

相关文章

  • leetcode-119-easy
    Pascal'sTriangleIIGivenanintegerrowIndex,returntherowIndexth(0-indexed)rowofthePascal'striangle.InPascal'striangle,eachnumberisthesumo......
  • leetcode-112-easy
    PathSumGiventherootofabinarytreeandanintegertargetSum,returntrueifthetreehasaroot-to-leafpathsuchthataddingupallthevaluesalongthe......
  • leetcode-628-easy
    MaximumProductofThreeNumbersGivenanintegerarraynums,findthreenumberswhoseproductismaximumandreturnthemaximumproduct.Example1:Input:n......
  • leetcode-1399-easy
    CountLargestGroupYouaregivenanintegern.Eachnumberfrom1tonisgroupedaccordingtothesumofitsdigits.Returnthenumberofgroupsthathave......
  • 力扣 leetcode 45. 跳跃游戏 II
    问题描述给你一个非负整数数组nums,你最初位于数组的第一个位置。数组中的每个元素代表你在该位置可以跳跃的最大长度。你的目标是使用最少的跳跃次数到达数组的最后一......
  • leetcode 1976.到达目的地的方案数
    问题描述:你在一个城市里,城市由n 个路口组成,路口编号为 0 到 n-1 ,某些路口之间有双向 道路。输入保证你可以从任意路口出发到达其他任意路口,且任意两个路口之间......
  • 力扣 leetcode 1758. 生成交替二进制字符串的最少操作数
    问题描述给你一个仅由字符'0'和'1'组成的字符串s。一步操作中,你可以将任一'0'变成'1',或者将'1'变成'0'。交替字符串定义为:如果字符串中不存在相邻两个字......
  • 对比山海鲸可视化跟EasyV,你更看好谁?
    现代的数据可视化设计一般喜欢追求更加高效的工具,我们在选择可视化工具的时候,一定会被繁多的可视化产品晃得眼花缭乱。今天给大家推荐2款我用过的可视化软件,不谈缺陷,只看优......
  • [LeetCode] 1758. Minimum Changes To Make Alternating Binary String
    Youaregivenastring s consistingonlyofthecharacters '0' and '1'.Inoneoperation,youcanchangeany '0' to '1' orviceversa.Thestringisc......
  • 螺旋矩阵II-LeetCode59 考验代码能力
    力扣链接:https://leetcode.cn/problems/spiral-matrix-ii/题目  给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 nxn 正方......