题目

类型:双指针

image.png

解题思路

每次都使用 i 和 j 分别指向左端和右端可以被交换的字母,若当前指针指向的不是字母,则分别往中间移动,直到找到下一个可交换的字母位置,每次交换结束,两指针均往中间移动一位。

代码

  1. class Solution {
  2. public String reverseOnlyLetters(String s) {
  3. char[] cs = s.toCharArray();
  4. int n = cs.length;
  5. for (int i = 0, j = n - 1; i < j; ) {
  6. while (i < j && !Character.isLetter(cs[i])) i++;
  7. while (i < j && !Character.isLetter(cs[j])) j--;
  8. if (i < j) {
  9. char c = cs[i];
  10. cs[i++] = cs[j];
  11. cs[j--] = c;
  12. }
  13. }
  14. return String.valueOf(cs);
  15. }
  16. }