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.html
Example 1:git
Input: "ab-cd" Output: "dc-ba"
Example 2:github
Input: "a-bC-dEf-ghIj" Output: "j-Ih-gfE-dCba"
Example 3:app
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 中對應的位置,參見代碼以下:code
解法一:htm
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,這樣也能夠實現只翻轉字母的目的,參見代碼以下:blog
解法二:leetcode
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