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.
这题就是字符串首位交换的题目,只是碰到非字母跳过即可。
class Solution {
public:
static int Test() {
auto res = Main("ab-cd");
return 0;
}
static bool isLetter(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
static string Main(string S) {
int fi = 0, li = S.length() - 1;
while (fi < li) {
if (!isLetter(S[fi])) {
fi++;
continue;
}
while (li >= 0 && !isLetter(S[li])) {
li--;
}
if (li <= fi) {
break;
}
std::swap(S[fi], S[li]);
fi++;
li--;
}
return S;
}
};