Tag Archives: well formed
C# || Longest Valid Parentheses – How To Find The Longest Valid Well Formed Parentheses Using C#
The following is a module with functions which demonstrates how to find the longest valid well formed parentheses using C#.
1. Longest Valid Parentheses – Problem Statement
Given a string containing just the characters ‘(‘ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".
Example 2:
Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".
Example 3:
Input: s = ""
Output: 0
2. Longest Valid Parentheses – Solution
The following is a solution which demonstrates how to find the longest valid well formed parentheses.
In this solution we can make use of a stack while scanning the given string to:
- Check if the string scanned so far is valid
- Find the length of the longest valid string
In order to do so, we start by pushing -1 onto the stack. For every ‘(‘ encountered, we push its index onto the stack.
For every ‘)‘ encountered, we pop the topmost element. Then, the length of the currently encountered valid string of parentheses will be the difference between the current element’s index and the top element of the stack.
If, while popping the element, the stack becomes empty, we will push the current element’s index onto the stack. In this way, we can continue to calculate the length of the valid substrings and return the length of the longest valid string at the end.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 24, 2022 // Taken From: http://programmingnotes.org/ // File: Solution.cs // Description: Demonstrates how to find the longest valid parentheses // ============================================================================ public class Solution { public int LongestValidParentheses(string s) { var result = 0; var stack = new Stack<int>(); stack.Push(-1); for (var index = 0; index < s.Length; ++index) { if (s[index] == '(') { stack.Push(index); } else { stack.Pop(); if (stack.Count == 0) { stack.Push(index); } else { result = Math.Max(result, index - stack.Peek()); } } } return result; } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output for the example cases:
2
4
0
C# || How To Find All Combinations Of Well-Formed Brackets Using C#
The following is a program with functions which demonstrates how to find all combinations of well-formed brackets using C#.
The task is to write a function Brackets(int n) that prints all combinations of well-formed brackets from 1…n. For example, Brackets(3), the output would be:
()
(()) ()()
((())) (()()) (())() ()(()) ()()()
The number of possible combinations is the Catalan number of N pairs C(n).
1. Find All Well-Formed Brackets
The example below demonstrates the use of the ‘Brackets‘ function to find all the well-formed bracket combinations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
// ============================================================================ // Author: Kenneth Perkins // Date: Sep 1, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: Generate all combinations of well-formed brackets from 1…n // ============================================================================ using System; using System.Collections.Generic; public class Program { static void Main(string[] args) { var results = Brackets(4); foreach (var result in results) { Console.WriteLine("Pair: " + result.pair + ", Combination: " + result.combination); } Console.ReadLine(); } /// <summary> /// Returns all combinations of well-formed brackets from 1...n /// </summary> /// <param name="pairs">The number of bracket combinations to generate</param> /// <param name="open">Optional. The 'open bracket' symbol</param> /// <param name="close">Optional. The 'close bracket' symbol</param> /// <returns>A List of bracket combination info</returns> public static List<Result> Brackets(int pairs, string open = "(", string close = ")") { var results = new List<Result>(); var symbols = new Symbols { open = open, close = close }; for (int pair = 1; pair <= pairs; ++pair) { var result = new Result { pair = pair, combination = BuildBrackets("", 0, 0, pair, symbols) }; results.Add(result); } return results; } public static string BuildBrackets(string output, int open, int close, int pair, Symbols symbols) { if ((open == pair) && (close == pair)) { return output; } string result = ""; if (open < pair) { string openCombo = BuildBrackets(output + symbols.open, open + 1, close, pair, symbols); if (openCombo.Length > 0) { result += (result.Length > 0 ? ", " : "") + openCombo; } } if (close < open) { string closeCombo = BuildBrackets(output + symbols.close, open, close + 1, pair, symbols); if (closeCombo.Length > 0) { result += (result.Length > 0 ? ", " : "") + closeCombo; } } return result; } public class Result { public int pair { get; set; } public string combination { get; set; } } public class Symbols { public string open { get; set; } public string close { get; set; } } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
Pair: 1, Combination: ()
Pair: 2, Combination: (()), ()()
Pair: 3, Combination: ((())), (()()), (())(), ()(()), ()()()
Pair: 4, Combination: (((()))), ((()())), ((())()), ((()))(), (()(())), (()()()), (()())(), (())(()), (())()(), ()((())), ()(()()), ()(())(), ()()(()), ()()()()
C++ || How To Find All Combinations Of Well-Formed Brackets Using C++
The following is a program with functions which demonstrates how to find all combinations of well-formed brackets.
The task is to write a function Brackets(int n) that prints all combinations of well-formed brackets from 1…n. For example, Brackets(3), the output would be:
()
(()) ()()
((())) (()()) (())() ()(()) ()()()
The number of possible combinations is the Catalan number of N pairs C(n).
1. Find All Well-Formed Brackets
The example below demonstrates the use of the ‘brackets‘ function to find all the well-formed bracket combinations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
// ============================================================================ // Author: Kenneth Perkins // Date: Oct 7, 2020 // Taken From: http://programmingnotes.org/ // File: generateParenthesis.cpp // Description: Generate all combinations of well-formed brackets from 1…n // ============================================================================ #include <iostream> #include <vector> #include <string> struct result { int pair; std::string combination; }; struct symbols { std::string open; std::string close; }; std::string buildBrackets(std::string output, int open, int close, int pair, symbols symbols) { if ((open == pair) && (close == pair)) { return output; } std::string result = ""; if (open < pair) { std::string openCombo = buildBrackets(output + symbols.open, open + 1, close, pair, symbols); if (openCombo.length() > 0) { result += (result.length() > 0 ? ", " : "") + openCombo; } } if (close < open) { std::string closeCombo = buildBrackets(output + symbols.close, open, close + 1, pair, symbols); if (closeCombo.length() > 0) { result += (result.length() > 0 ? ", " : "") + closeCombo; } } return result; } /** * FUNCTION: brackets * USE: Returns all combinations of well-formed brackets from 1...n * @param pairs: The number of bracket combinations to generate. * @param open: Optional. The 'open bracket' symbol. * @param close: Optional. The 'close bracket' symbol. * @return: An array of bracket combination info. */ std::vector<result> brackets(int pairs, std::string open = "(", std::string close = ")") { std::vector<result> results; symbols symbols{open, close}; for (int pair = 1; pair <= pairs; ++pair) { result result{pair, buildBrackets("", 0, 0, pair, symbols)}; results.push_back(result); } return results; } int main() { std::vector<result> results = brackets(4); for (auto const &result : results) { std::cout << "Pair: " << result.pair << ", Combination: " << result.combination << std::endl; } std::cin.get(); return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
Pair: 1, Combination: ()
Pair: 2, Combination: (()), ()()
Pair: 3, Combination: ((())), (()()), (())(), ()(()), ()()()
Pair: 4, Combination: (((()))), ((()())), ((())()), ((()))(), (()(())), (()()()), (()())(), (())(()), (())()(), ()((())), ()(()()), ()(())(), ()()(()), ()()()()