Home > Software engineering >  C#, Finding equal amount of brackets
C#, Finding equal amount of brackets

Time:12-08

I've made my own way to check if the amount of () and "" are equal. So for example "H(ell)o") is correct. However, the problem I face is that what if the first bracket is ) and the other is ( example "H)ell(o" this would mean it's incorrect. So my question is how would I check whether the first bracket in any word is opening?

EDIT:

        public static Boolean ArTinkaSintakse(char[] simboliai)
        {
            int openingBracketsAmount = 0;
            int closingBracketsAmount = 0;
            int quotationMarkAmount = 0;

            for (int i = 0; i < simboliai.Length; i  )
            {
                if (openingBracketsAmount == 0 && simboliai[i] == ')')
                    break;

                else if (simboliai[i] == '\"')
                    quotationMarkAmount  ;

                else if (simboliai[i] == '(')
                    openingBracketsAmount  ;

                else if (simboliai[i] == ')')
                    closingBracketsAmount  ;
            }

            int bracketAmount = openingBracketsAmount   closingBracketsAmount;

            if (quotationMarkAmount % 2 == 0 && bracketAmount % 2 == 0)
                return true;
            else
                return false;
        }

CodePudding user response:

Add a check for if (openingBracketsAmount < closingBracketsAmount). If that's ever true, you know that the brackets are unbalanced.

CodePudding user response:

Add an if statement that breaks out of the loop if the first bracket encountered is a closing bracket, like so:

for (int i = 0; i < word.Length; i  )
{
    if ((openingBracketsAmount == 0) && (word[i] == ')'))
    {
        <Log error...>
        break;
    }

    <Rest of your loop...>
}

This way, as soon as openingBracketsAmount is updated, this if statement will be unreachable.

CodePudding user response:

I would approach the problem recursively.

Create a Dictionary<char, char> to keep track of which opening character goes with which closing one.

Then I would implement: boolean findMatches(string input, out int lastIndex) {}

The method will scan until a member of the Dictionary keys is found. Then it will recursively call itself with the remainder of the string. If the recursive call comes back false, return that. If true, check if the lastIndex character (or the one after; I always need to write the code to check fenceposts) is the matching bracket you want. If it is, and you're not at the end of the string, return the value of a recursive call with the rest of the string after that matching bracket. If you are at the end, return true with that character's index. If that character isn't the matching bracket/quote, pass the remainder of the string (including that last character) to another recursive call.

Continue until you reach the end of the string (returning true if you aren't matching a bracket or quote, false otherwise). Either way with a lastIndex of the last character.

CodePudding user response:

Probably you need a stack-based approach to validate such expressions.
Please try the following code:

public static bool IsValid(string s)
{
    var pairs = new List<Tuple<char, char>>
    {
        new Tuple<char, char>('(', ')'),
        new Tuple<char, char>('{', '}'),
        new Tuple<char, char>('[', ']'),
    };

    var openTags = new HashSet<char>();
    var closeTags = new Dictionary<char, char>(pairs.Count);
    foreach (var p in pairs)
    {
        openTags.Add(p.Item1);
        closeTags.Add(p.Item2, p.Item1);
    }

    // Remove quoted parts
    Regex r = new Regex("\".*?\"", RegexOptions.Compiled | RegexOptions.Multiline);
    s = r.Replace(s, string.Empty);

    var opened = new Stack<char>();
    foreach (var ch in s)
    {
        if (ch == '"')
        {
            // Unpaired quote char
            return false;
        }
        if (openTags.Contains(ch))
        {
            // This is a legal open tag
            opened.Push(ch);
        }
        else if (closeTags.TryGetValue(ch, out var openTag) && openTag != opened.Pop())
        {
            // This is an illegal close tag or an unbalanced legal close tag
            return false;
        }
    }

    return true;
}
  •  Tags:  
  • c#
  • Related