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
// 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"));
}
}
}
Comments
Leave a comment