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"
這道題給了一個由字母和其他字符組成的字符串,讓我們只翻轉其中的字母,並不是一道難題,解題思路也比較直接。可以先反向遍歷一遍字符串,只要遇到字母就直接存入到一個新的字符串 res,這樣就實現了對所有字母的翻轉。但目前的 res 中就只有字母,還需要將原字符串S中的所有的非字母字符加入到正確的位置,可以再正向遍歷一遍原字符串S,遇到字母就跳過,否則就把非字母字符加入到 res 中對應的位置,參見代碼如下:
解法一:
class Solution {
public:
string reverseOnlyLetters(string S) {
string res = "";
for (int i = (int)S.size() - 1; i >= 0; --i) {
if (isalpha(S[i])) res.push_back(S[i]);
}
for (int i = 0; i < S.size(); ++i) {
if (isalpha(S[i])) continue;
res.insert(res.begin() + i, S[i]);
}
return res;
}
};
再來看一種更加簡潔的解法,使用兩個指針i和j,分別指向S串的開頭和結尾。當i指向非字母字符時,指針i自增1,否則若j指向非字母字符時,指針j自減1,若i和j都指向字母時,則交換 S[i] 和 S[j] 的位置,同時i自增1,j自減1,這樣也可以實現只翻轉字母的目的,參見代碼如下:
解法二:
class Solution {
public:
string reverseOnlyLetters(string S) {
int n = S.size(), i = 0, j = n - 1;
while (i < j) {
if (!isalpha(S[i])) ++i;
else if (!isalpha(S[j])) --j;
else {
swap(S[i], S[j]);
++i; --j;
}
}
return S;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/917
參考資料:
https://leetcode.com/problems/reverse-only-letters/
https://leetcode.com/problems/reverse-only-letters/discuss/178419/JavaC%2B%2BPython-Two-Pointers
[LeetCode All in One 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)