Valid Parentheses


/ Published in: C++
Save to your folder(s)

leetcode.com


Copy this code and paste it in your HTML
  1. /** \file Valid Parentheses.cpp
  2.   * \details
  3.   * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
  4.   * The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
  5.   * \author LOC
  6.   */
  7.  
  8. #include <iostream>
  9. #include <cstring>
  10. using namespace std;
  11.  
  12. //! \brief check string is valid? return true if valid otherwise false
  13. //! \param string[] a string which entered from keyboard
  14. //! \return true if valid and false if invalid
  15. bool Solution(char string[]){
  16. int length = strlen(string);
  17. for(int i=0; i<length; i+=2){
  18. if((string[i]=='[' && string[i+1]==']') || (string[i]=='{' && string[i+1]=='}') || (string[i]=='(' && string[i+1]==')') )
  19. return true;
  20. else return false;
  21. }
  22. }
  23.  
  24. int main(){
  25. char string[10];
  26. cout < "Enter a string";
  27. cin.getline(string,10);
  28. if (Solution(string)) cout << "Your string is valid";
  29. else cout << "Your string is invalid";
  30. return 0;
  31. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.