Created
October 14, 2024 05:33
-
-
Save unilecs/cea7e9c58a124368aac03438d6fadc02 to your computer and use it in GitHub Desktop.
Задача: Реверс подстрок между скобками
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment