fork download
  1. #include <iostream>
  2. #include <stack>
  3.  
  4. int countSentences(const std::string& input)
  5. {
  6. int len = static_cast<int>(input.length());
  7. int countValidSentences = 0;
  8. int countInvalidSentences = 0;
  9.  
  10. std::stack<char> leftParenthesis;
  11.  
  12. for(int i = 0; i < len; i++)
  13. {
  14. if(input[i] == '(')
  15. {
  16. leftParenthesis.push(input[i]);
  17. }
  18. else if(input[i] == ')')
  19. {
  20. if(leftParenthesis.empty() || leftParenthesis.top() != '(')
  21. {
  22. countInvalidSentences++;
  23. }
  24. else
  25. {
  26. leftParenthesis.pop();
  27. countValidSentences++;
  28. }
  29. }
  30. }
  31.  
  32. countInvalidSentences += leftParenthesis.size();
  33. int calculateValidSentencesFromInvalid = countInvalidSentences / 2;
  34.  
  35. return countValidSentences + calculateValidSentencesFromInvalid;
  36. }
  37.  
  38. int main()
  39. {
  40. std::string input;
  41. std::cin >> input;
  42.  
  43. int ret = countSentences(input);
  44. std::cout << ret;
  45. return 0;
  46. }
Success #stdin #stdout 0s 5288KB
stdin
()(())))
stdout
4