LeetCode-917 仅仅反转字母

917. 仅仅反转字母

Difficulty: 简单

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

示例 1:

输入:"ab-cd"
输出:"dc-ba"

示例 2:

输入:"a-bC-dEf-ghIj"
输出:"j-Ih-gfE-dCba"

示例 3:

输入:"Test1ng-Leet=code-Q!"
输出:"Qedo1ct-eeLg=ntse-T!"

提示:

  1. S.length <= 100
  2. 33 <= S[i].ASCIIcode <= 122
  3. S 中不包含 \ or "

Solution

Language: C++

​class Solution {
public:
    string reverseOnlyLetters(string S) {
        int lo = 0;int hi = S.length() - 1;
        while (lo<hi) {
            while (lo<=hi && !isAlpha(S,lo)) {
                lo++;
            }
            while (hi>lo && !isAlpha(S,hi)) {
                hi--;
            }
            if (lo < hi) {
                S[lo] = S[lo] ^ S[hi];
                S[hi] = S[lo] ^ S[hi];
                S[lo] = S[lo] ^ S[hi];
            }
            lo++;
            hi--;
        } 
        return S;
    }
    bool isAlpha(string &S,int lo){
        return (S[lo] >= 'A' && S[lo] <= 'Z') || (S[lo] >= 'a' && S[lo] <= 'z');
    }
};