# 917.Reverse Only Letters

**917.Reverse Only Letters**

难度:Easy

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

```
示例 1：

输入："ab-cd"
输出："dc-ba"
示例 2：

输入："a-bC-dEf-ghIj"
输出："j-Ih-gfE-dCba"
示例 3：

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

提示：

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

利用一个string存储所有字母，然后将逆序字母和非字母合并。

```
class Solution {
public:
    string reverseOnlyLetters(string S) {
        string alpha;
        string res;
        for(auto c:S)
            if((c>='a' && c<='z' ) || (c>='A' && c<='Z')  ) 
                alpha+=c;
        int start=0;
        int len=alpha.length();
        for(int i=0;i<S.length();i++)
        {
            if((S[i] >= 'a' && S[i]<='z') || (S[i]>='A'  && S[i] <='Z')) 
                res+=alpha[len-1-start++];
            else 
                res+=S[i];
        }
            return res;
    }
};
```

> 执行用时 :0 ms, 在所有 C++ 提交中击败了100%的用户\
> 内存消耗 :8.2MB, 在所有 C++ 提交中击败了82.89%的用户


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/917.reverse_only_letters.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
