Blogs Hub

Reverse Only Letters - MiniTV

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)