Answer to Question #243458 in C# for Gayatri

Question #243458

1. Given a sequence of brackets, write a method that checks if it has the same number of opening and closing brackets.

Expected input and output

CheckBracketsSequence("((()))") → true

CheckBracketsSequence("()(())(") → false

CheckBracketsSequence(")") → false

2. Given a string, write a method that counts its number of words. Assume there are no leading and trailing whitespaces and there is only single whitespace between two consecutive words.

Expected input and output

NumberOfWords("This is sample sentence") → 4

NumberOfWords("OK") → 1


1
Expert's answer
2021-10-01T16:52:46-0400
// first
using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    internal class Program
    {
        public static bool CheckBracketsSequence(string str)
        {
            var stack = new Stack<char>();
            foreach (var symbol in str)
            {
                if (symbol == '(')
                    stack.Push(symbol);
                else
                    try
                    {
                        stack.Pop();
                    }
                    catch (Exception e)
                    {
                        return false;
                    }
                    
            }
            return stack.Count == 0;
        }
        public static void Main(string[] args)
        {
            Console.WriteLine(CheckBracketsSequence("(())"));
        }
    }
}

// second
using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    internal class Program
    {
        public static int NumberOfWords(string str)
        {
            var words = str.Split(' ');
            return words.Length;
        }
        public static void Main(string[] args)
        {
            Console.WriteLine(NumberOfWords("This is sample sentence"));
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS