题目:
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!”Note:
S.length <= 100 33 <= S[i].ASCIIcode <= 122 S doesn’t contain \ or "
解释:
题目要求一目了然,仅仅翻转字母,不翻转其他符号,用python实现很方便,遍历两遍即可,cpp的写法需要学习一下。
python代码:
class Solution:
def reverseOnlyLetters(self, S):
"""
:type S: str
:rtype: str
"""
letters=[]
for letter in S:
if letter.isalpha():
letters.append(letter)
letters=letters[::-1]
idx=0
S=list(S)
for i in range(len(S)):
if S[i].isalpha():
S[i]=letters[idx]
idx+=1
return ''.join(S)
注意,python中不能直接给字符串额的元素赋值,需要转成list才能赋值。
c++代码:
#include<cctype>
#include<algorithm>
//cctype中有一个函数是int islapha(char)
//algprithm中有一个reverse函数可以实现容器的翻转
class Solution {
public:
string reverseOnlyLetters(string S) {
vector<char>letters;
for(auto letter:S)
{
if (isalpha(letter))
letters.push_back(letter);
}
reverse(letters.begin(),letters.end());
int idx=0;
for (int i=0;i<S.size();i++)
{
if (isalpha(S[i]))
{
S[i]=letters[idx++];
}
}
return S;
}
};
总结:
学会使用c++中的库函数,cctype中的isalpha(),algorithm中的reverse()。