classSolution: defreverseOnlyLetters(self, s: str) -> str: ans = list(s) left, right = 0, len(ans) - 1 whileTrue: while left < right andnot ans[left].isalpha(): # 判断左边是否扫描到字母 left += 1 while right > left andnot ans[right].isalpha(): # 判断右边是否扫描到字母 right -= 1 if left >= right: break ans[left], ans[right] = ans[right], ans[left] left += 1 right -= 1 return''.join(ans)
classSolution { public: string reverseOnlyLetters(string s){ int n = s.size(); int left = 0, right = n - 1; while (true) { while (left < right && !isalpha(s[left])) { // 判断左边是否扫描到字母 left++; } while (right > left && !isalpha(s[right])) { // 判断右边是否扫描到字母 right--; } if (left >= right) { break; } swap(s[left], s[right]); left++; right--; } return s; } };
char *reverseOnlyLetters(char *s){ int n = strlen(s); int left = 0, right = n - 1; while (true) { while (left < right && !isalpha(s[left])) { // 判断左边是否扫描到字母 left++; } while (right > left && !isalpha(s[right])) { // 判断右边是否扫描到字母 right--; } if (left >= right) { break; } swap(s + left, s + right); left++; right--; } return s; }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
funcreverseOnlyLetters(s string)string { ans := []byte(s) left, right := 0, len(s)-1 for { for left < right && !unicode.IsLetter(rune(s[left])) { // 判断左边是否扫描到字母 left++ } for right > left && !unicode.IsLetter(rune(s[right])) { // 判断右边是否扫描到字母 right-- } if left >= right { break } ans[left], ans[right] = ans[right], ans[left] left++ right-- } returnstring(ans) }