Skip to content

917. Reverse Only Letters 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  string reverseOnlyLetters(string s) {
    for (int i = 0, j = s.length() - 1; i < j; ++i, --j) {
      while (i < j && !isalpha(s[i]))
        ++i;
      while (i < j && !isalpha(s[j]))
        --j;
      swap(s[i], s[j]);
    }
    return s;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public String reverseOnlyLetters(String s) {
    StringBuilder sb = new StringBuilder(s);

    for (int i = 0, j = s.length() - 1; i < j; ++i, --j) {
      while (i < j && !Character.isLetter(s.charAt(i)))
        ++i;
      while (i < j && !Character.isLetter(s.charAt(j)))
        --j;
      sb.setCharAt(i, s.charAt(j));
      sb.setCharAt(j, s.charAt(i));
    }

    return sb.toString();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def reverseOnlyLetters(self, s: str) -> str:
    ans = list(s)
    i = 0
    j = len(s) - 1

    while i < j:
      while i < j and not s[i].isalpha():
        i += 1
      while i < j and not s[j].isalpha():
        j -= 1
      ans[i], ans[j] = ans[j], ans[i]
      i += 1
      j -= 1

    return ''.join(ans)