资讯专栏INFORMATION COLUMN

[LeetCode] 917. Reverse Only Letters

superw / 2866人阅读

Problem

Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.

Example 1:

Input: "ab-cd"
Output: "dc-ba"
Example 2:

Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"
Example 3:

Input: "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"

Note:

S.length <= 100
33 <= S[i].ASCIIcode <= 122 
S doesn"t contain  or "
Solution
class Solution {
    public String reverseOnlyLetters(String S) {
        char[] str = S.toCharArray();
        int i = 0, j = str.length-1;
        while (i < j) {
            while (i < j && !Character.isLetter(str[i])) i++;
            while (i < j && !Character.isLetter(str[j])) j--;
            swap(str, i++, j--);
        }
        StringBuilder sb = new StringBuilder();
        sb.append(str);
        return sb.toString();
    }
    private void swap(char[] str, int i, int j) {
        char temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72095.html

相关文章

  • Leetcode PHP题解--D63 917. Reverse Only Letters

    摘要:题目链接题目分析给定一个包含符号的字符串,仅倒转字母的出现顺序,不改变符号的出现位置。思路先把字符串分成字母和符号两部分,保留下标。抽离字母数组的键和值,对值部分进行倒转,合并到键数组中。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 D63 917. Reverse Only Letters 题目链接 917. Reverse Only Letters 题目分析 给定一个包含符号的...

    binaryTree 评论0 收藏0
  • LeetCode[316] Remove Duplicate Letters

    摘要:复杂度思路用一个每次考虑当前的字符大小和的顶端字符的大小,如果当前字符比较小的话,则可以出顶端的字符,将当前的字符放进中。需要维持了一个判断当前字符在剩余字符串中的出现次数,考虑能否将这个字符从栈中弹出。 LeetCode[316] Remove Duplicate Letters Given a string which contains only lowercase letter...

    tomorrowwu 评论0 收藏0
  • [LeetCode]Remove Duplicate Letters

    摘要:首先要求就是得保证在原来的字符串中存在当前字符的顺序,即要保证每次的字符的次数大于。读字符的过程中,把字符存到里,当发现之前存的字符中比当前字符大而且频率还大于就可以把那个字符出去。基本思想就是在一定的限制条件下出比当前选择差的元素。 Remove Duplicate Letters Given a string which contains only lowercase lette...

    gaosboy 评论0 收藏0
  • 翻转字符串的相关题目

    摘要:一题目描述空格分隔,逐个反转二题目描述三题目描述当然也可以用的做,不过用双指针更快。 LeetCode: 557. Reverse Words in a String III 一、LeetCode: 557. Reverse Words in a String III 题目描述 Given a string, you need to reverse the order of chara...

    lykops 评论0 收藏0
  • [LeetCode] 482. License Key Formatting

    Problem You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes. Given a number K, we would wan...

    codercao 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<