LeetCode-Reverse Only Letters

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/82982636

Description:
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 "

题意:给定一个字符串,将字符串中所有的字母逆序(即只有当两个要交换的位置都是字母时才可以交换);

解法:我们分别从首尾处开始向中间遍历,找到出现的首个字母,进行交换,重复这个操作,直到首尾处的遍历相遇;

Java
class Solution {
    public String reverseOnlyLetters(String S) {
        int st = 0;
        int ed = S.length() - 1;
        StringBuilder result = new StringBuilder(S);
        while (st < ed) {
            while (st < S.length() && !Character.isAlphabetic(S.charAt(st))) st++;
            while (ed >= 0 && !Character.isAlphabetic(S.charAt(ed))) ed--;
            if (st >= ed) break;
            result.replace(st, st + 1, S.charAt(ed) + "");
            result.replace(ed, ed + 1, S.charAt(st) + "");
            st++;
            ed--;
        }
        return result.toString();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/82982636