PROGRAMING/C#

[Algorithm] Determine matching parentheses

donghunl 2024. 5. 15. 07:00
반응형

Question :

In this challenge, you'll develop a fuction that determinesif agiven piece of text has matching parentheses.

we define matching parentheses as a set of symbols that have an opening symobl with a corresponding closing symbol.

The opening symbol msut also come before the closing symbol.

Although parentheses are traditionally curved characters ( ), we are also considering square brackets [ ] and arrow brackets < > parentheses-like symbols as well.

 

Return true or false depending on whether the input string has matching parentheses or not.

입력 받은 문자열중에 괄호가 매칭이 되는지를 확인 하는 문제 입니다.

 

Solution :

Dictionary로 매칭 괄호들을 정의하고 Dictoinary안에 해당 괄호가 존재하면 Stack에 집어 넣은 후 벨류값으로 키값을 찾아나감으로써 매칭을 찾을수 있습니다.

public static Boolean HasMatchingParentheses(string s) {
    // Your code goes here.
    Stack<char> stack = new Stack<char>();
    Dictionary<char, char> blockSymbols = new Dictionary<char, char>{
        {')', '('},
        {']', '['},
        {'>', '<'}
    };

    for (int i = 0; i < s.Length; i++) {
        char current = s[i];
        if ( blockSymbols.ContainsValue(current)) {
            stack.Push(current);
            //Console.WriteLine("Stack : " + i + " " + current);
        }

        if (blockSymbols.ContainsKey(current) && // check the keys in symbols map
            (stack.Count == 0 ||                 // stack empty check or
                blockSymbols.GetValueOrDefault(current) != stack.Pop())) { // stack value is not in symbos map
                    return false;
        }
    }

    return stack.Count == 0;
}

 

반응형

'PROGRAMING > C#' 카테고리의 다른 글

[Algorithm] Sort Colors  (3) 2024.05.04
[Algorithm] The smallest possible integer after removing k  (2) 2024.05.04
[Algorithm] Reverse each word  (5) 2024.05.02
[Algorithm] Valid Palindrome  (69) 2024.04.30
[Algorithm] Palindrome Number  (92) 2024.04.27