ReverseParentheses.cs

CSharp · Console

/Program.cs

using System;
using System.Text;
using System.Collections.Generic;
					
public class Program
{
	public static void Reverse(StringBuilder sb, int start, int end) {
        while (start < end) {
            char temp = sb[start];
            sb[start] = sb[end];
            sb[end] = temp;
            start++;
            end--;
        }
    }

    public static string ReverseParentheses(string s) {
        var stack = new Stack<int>();
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < s.Length; i++) {
            if (s[i] == '(') {
                // сохраняем позицию открывающейся скобки
                stack.Push(res.Length);
            } else if (s[i] == ')') {
                // берем позицию последней открывающейся скобки
                int start = stack.Pop();

                // делаем реверс подстроки
                Reverse(res, start, res.Length - 1);
            }
            else {
                res.Append(s[i]);
            }
        }

        return res.ToString();
    }
	
	public static void Main()
	{
		Console.WriteLine("UniLecs");
		
		// tests
		Console.WriteLine(ReverseParentheses("(abcd)")); // dcba
		Console.WriteLine(ReverseParentheses("(u(love)i)")); // iloveu
	}
}
;