Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace ConsoleApp1;
- using System.Text;
- public class Task18
- {
- public void Run()
- {
- Console.InputEncoding = Encoding.Unicode;
- Console.OutputEncoding = Encoding.Unicode;
- char openingBracket = '(';
- char closingBracket = ')';
- bool canExit = false;
- while ( canExit == false )
- {
- Console.Clear();
- Console.WriteLine("Input text with brackets");
- string text = Console.ReadLine();
- int bracketsAccumulator = 0;
- int maximumNestingDepth = 0;
- bool isTextCorrect = true;
- int firstUnexpectedClosingBracketIndex = -1;
- for ( var index = 0; index < text.Length; index++ )
- {
- var symbol = text[index];
- if ( symbol == openingBracket )
- {
- bracketsAccumulator++;
- }
- else if ( symbol == closingBracket )
- {
- bracketsAccumulator--;
- }
- maximumNestingDepth = Math.Max( bracketsAccumulator, maximumNestingDepth );
- if ( isTextCorrect && bracketsAccumulator < 0 )
- {
- isTextCorrect = false;
- firstUnexpectedClosingBracketIndex = index;
- }
- }
- if ( isTextCorrect && bracketsAccumulator != 0 )
- {
- isTextCorrect = false;
- }
- if ( isTextCorrect )
- {
- Console.WriteLine($"Text is correct, maximum nesting depth = {maximumNestingDepth}");
- }
- else if( firstUnexpectedClosingBracketIndex != -1 )
- {
- Console.WriteLine( $"Text is not valid, maximum nesting depth = {maximumNestingDepth}, has unexpected close bracket, index = {firstUnexpectedClosingBracketIndex}" );
- }
- else
- {
- Console.WriteLine( $"Text is not valid, maximum nesting depth = {maximumNestingDepth}, missing closing bracket" );
- }
- Console.WriteLine();
- string properlyExitAnswer = "n";
- Console.WriteLine( $"Continue? Enter \'{properlyExitAnswer}\' for exit" );
- string continueAnswer = Console.ReadLine();
- canExit = string.Equals( continueAnswer, properlyExitAnswer );
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement