题目来源: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;
}
};