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 "
Ideas of solving problems
In solving this problem, we should choose two Pointers.The first pointer starts at the beginning and the second pointer starts at the end.You just have to decide if it’s a letter and reverse it.We can use ASCII code to determine whether a string is a letter or a character. The time complexity is O(n), and the space complexity is O(n). The memory consumption is 2Mb.
Code
func reverseOnlyLetters(S string) string {
var left,right int = 0,len(S) - 1
for left < right {
if isLetter(S[left]) && isLetter(S[right]) {
S = S[:left] + string(S[right]) + S[left + 1:right] + string(S[left]) + S[right + 1:]
left++
right--
}
if !isLetter(S[left]) {
left++
}
if !isLetter(S[right]) {
right--
}
}
return S
}
func isLetter(a byte) bool {
if (a >= 65 && a <= 90) || (a >= 97 && a <= 122) {
return true
}
return false
}
链接:https://leetcode-cn.com/problems/reverse-only-letters/solution/917jin-jin-fan-zhuan-zi-mu-by-wang-xiao-zhu-3/
来源:力扣(LeetCode)