给定一个字符串 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"
/**
* @param {string} S
* @return {string}
*/
var reverseOnlyLetters = function (S) {
let stk = [];
let out = "";
for (let i = 0; i < S.length; i++) {
if ((S.charCodeAt(i) >= 'A'.charCodeAt(0) && S.charCodeAt(i) <= 'Z'.charCodeAt(0)) || (S.charCodeAt(i) >= 'a'.charCodeAt(0) && S.charCodeAt(i) <= 'z'.charCodeAt(0))) {
stk.push(S.substring(i, i + 1));
}
}
for (let i = 0; i < S.length; i++) {
if ((S.charCodeAt(i) >= 'A'.charCodeAt(0) && S.charCodeAt(i) <= 'Z'.charCodeAt(0)) || (S.charCodeAt(i) >= 'a'.charCodeAt(0) && S.charCodeAt(i) <= 'z'.charCodeAt(0))) {
out = out + stk.pop();
} else {
out = out + S.substring(i, i + 1);
}
}
return out;
};