c++实现字符串反转
给定一个字符串 S
,返回 “反转后的” 字符串,其中不是字母的字符都保留在原地,而所有字母的位置发生反转。
示例 1:
输入:"ab-cd"
输出:"dc-ba"
示例 2:
输入:"a-bC-dEf-ghIj"
输出:"j-Ih-gfE-dCba"
示例 3:
输入:"Test1ng-Leet=code-Q!"
输出:"Qedo1ct-eeLg=ntse-T!"
链接:https://leetcode-cn.com/problems/reverse-only-letters
class Solution {
public:
bool isLetter(char ch)//判断字符是否是字母
{
if((ch<='z')&&(ch>='a'))
return true;
if((ch<='Z')&&(ch>='A'))
return true;
return false;
}
string reverseOnlyLetters(string S) {
if(S.empty())//检查是否是空字符串
{
return S;
}
int begin=0,end=S.size()-1;//头和尾的下标
while(begin<end)
{
while(begin<end && !isLetter(S[begin]))//不是字符,向后走
{
begin++;
}
while(begin<end && !isLetter(S[end]))//不是字符向前走
{
end--;
}
swap(S[begin],S[end]);//交换函数,c++中直接调用
begin++;
end--;
}
return S;
}
};