LeetCode Solutions

917. Reverse Only Letters

Time:

Space:

			

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;
  }
};
			

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();
  }
}
			

class Solution:
  def reverseOnlyLetters(self, S: str) -> str:
    S = 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
      S[i], S[j] = S[j], S[i]
      i += 1
      j -= 1

    return ''.join(S)