1. 程式人生 > >LeetCode周賽#105 Q1 Reverse Only Letters(字串逆序)

LeetCode周賽#105 Q1 Reverse Only Letters(字串逆序)

題目來源:https://leetcode.com/contest/weekly-contest-105/problems/reverse-only-letters/

問題描述

917. Reverse Only Letters

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!"

------------------------------------------------------------

題意

字串逆序,但要求保持字串中非英文字母的字元位置不變

------------------------------------------------------------

思路

設定兩個指標,一個指向原字串中字母的位置,一個指向逆序字串對應字母的位置,如遇非字母字元則跳過不處理。

------------------------------------------------------------

程式碼

class Solution {
public:
    string reverseOnlyLetters(string S) {
        int i, j, len = S.size();
        string R(S);
        i = 0;
        j = len-1;
        while (i < len && j >= 0)
        {
            while (!((S[i]>='a' && S[i]<='z') || (S[i]>='A' && S[i]<='Z')))
            {
                i++;
            }
            while (!((R[j]>='a' && R[j]<='z') || (R[j]>='A' && R[j]<='Z')))
            {
                j--;
            }
            if (i > len || j < 0)
            {
                break;
            }
            R[j--] = S[i++];
        }
        return R;
    }
};