Skip to content

Latest commit

 

History

History
58 lines (45 loc) · 1.37 KB

917. Reverse Only Letters.md

File metadata and controls

58 lines (45 loc) · 1.37 KB

917. Reverse Only Letters

https://leetcode.com/problems/reverse-only-letters/

Given a string s, reverse the string according to the following rules:

  • All the characters that are not English letters remain in the same position.
  • All the English letters (lowercase or uppercase) should be reversed.

Return s after reversing it.

Example 1:

Input: s = "ab-cd" Output: "dc-ba"

Example 2:

Input: s = "a-bC-dEf-ghIj" Output: "j-Ih-gfE-dCba"

Example 3:

Input: s = "Test1ng-Leet=code-Q!" Output: "Qedo1ct-eeLg=ntse-T!"

Constraints:

  • 1 <= s.length <= 100
  • s consists of characters with ASCII values in the range [33, 122].
  • s does not contain '\"' or '\\'.
public class Solution {
    public string ReverseOnlyLetters(string s) {
        var stack = new Stack<char>();
        var d = new Dictionary<int, char>();

        for (int i = 0; i < s.Length; i++)
        {
            if (char.IsLetter(s[i]))
                stack.Push(s[i]);
            else
                d.Add(i, s[i]);
        }
        var j = 0;
        var result = new StringBuilder();
        while (j != s.Length)
        {
            if (d.TryGetValue(j, out var c))
                result.Append(c);
            else
                result.Append(stack.Pop());
            j++;
        }
        return result.ToString();
    }
}