From 1bcb11adc62a644d8595f213a92780d1efe216d6 Mon Sep 17 00:00:00 2001 From: priyankaanandd Date: Fri, 31 Oct 2025 18:06:58 +0530 Subject: [PATCH] feat: Add Valid Parentheses problem in C++ --- .../Valid_Parentheses.cpp | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 c++ problems asked in interview/Valid_Parentheses.cpp diff --git a/c++ problems asked in interview/Valid_Parentheses.cpp b/c++ problems asked in interview/Valid_Parentheses.cpp new file mode 100644 index 0000000..e15bd95 --- /dev/null +++ b/c++ problems asked in interview/Valid_Parentheses.cpp @@ -0,0 +1,66 @@ +/* +* C++ Solution for the "Valid Parentheses" Problem +* +* Problem: Given a string s containing just the characters '(', ')', +* '{', '}', '[' and ']', determine if the input string is valid. +* An input string is valid if: +* 1. Open brackets must be closed by the same type of brackets. +* 2. Open brackets must be closed in the correct order. +* +* Contributor: Priyanka Anand +* Submitted for Hacktoberfest 2025 +*/ + +#include +#include +#include +#include + +class Solution { +public: + bool isValid(std::string s) { + std::stack charStack; + // Map to hold the valid pairs + std::unordered_map pairs = { + {')', '('}, + {']', '['}, + {'}', '{'} + }; + + for (char c : s) { + // If it's a closing bracket + if (pairs.count(c)) { + // Check if stack is empty or top element doesn't match + if (charStack.empty() || charStack.top() != pairs[c]) { + return false; // Invalid + } + charStack.pop(); // It's a valid pair, pop the opening bracket + } else { + // It's an opening bracket, push onto stack + charStack.push(c); + } + } + + // If the stack is empty, all brackets were matched + return charStack.empty(); + } +}; + +// Main function to test the solution +int main() { + Solution sol; + std::string str1 = "()[]{}"; + std::string str2 = "([)]"; + std::string str3 = "{[]}"; + + std::cout << "String \"" << str1 << "\" is valid: " + << (sol.isValid(str1) ? "true" : "false") << std::endl; + + std::cout << "String \"" << str2 << "\" is valid: " + << (sol.isValid(str2) ? "true" : "false") << std::endl; + + std::cout << "String \"" << str3 << "\" is valid: " + << (sol.isValid(str3) ? "true" : "false") << std::endl; + + return 0; +} \ No newline at end of file