Design PatternLeetCodeEasy

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');
    }
};
支付宝扫码打赏 微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏

扫描二维码,分享此文章

段连洁's Picture
段连洁

iOSer

Subscribe to JAY 站 | Share Thoughts

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!

Comments