Reverse Only Letters
💻 coding

Reverse Only Letters

1 min read 165 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to reverse only the letters in a given string while keeping non-letter characters in their original positions.
  • 2Examples demonstrate that input strings like 'ab-cd' and 'Test1ng-Leet=code-Q!' yield reversed letter outputs without altering non-letter characters.
  • 3The solution involves iterating through the string with two pointers, swapping letters while skipping non-letter characters, achieving O(n) time complexity.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to reverse only the letters in a given string while keeping non-letter characters in their original positions."

Reverse Only Letters

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 "

Solution:

using System;
using System.Collections.Generic;
using System.Text;

namespace LeetCode.AskGif.Easy.String
{
 class ReverseOnlyLettersSoln
 {
 public void execute()
 { 
 var res = ReverseOnlyLetters("a-bC-dEf-ghIj");
 }

 public string ReverseOnlyLetters(string S)
 {
 char[] str = new char[S.Length];
 for (int i = 0, j = S.Length-1; i < S.Length;)
 {
 if (IsLetter(S[i]) && IsLetter(S[j]))
 {
 str[i] = S[j];
 i++;
 j--;
 }
 else if (!IsLetter(S[i]))
 {
 str[i] = S[i];
 i++;
 }
 else if (!IsLetter(S[j]))
 {
 j--;
 }
 }

 return new string(str);
 }

 private bool IsLetter(char v)
 {
 return (v >= 97 && v <= 122) || (v >= 65 && v <= 90);
 }
 }
}

Time Complexity: O(n)

Space Complexity: O(n)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 6 May 2020 · 1 min read · 165 words

Part of AskGif Blog · coding

You might also like