Untitled
unknown
plain_text
23 days ago
872 B
2
Indexable
Never
#include <iostream> #include <string> // Function to check if the string belongs to the grammar bool checkString(const std::string& str) { // The string must end with a 'b' if (str.empty() || str.back() != 'b') { return false; } // Count the number of 'a' characters before the last 'b' size_t i = 0; while (i < str.length() - 1 && str[i] == 'a') { ++i; } // After counting 'a's, the rest of the string must be 'b' (exactly one 'b') return i == str.length() - 1; } int main() { std::string input; std::cout << "Enter the string to check: "; std::cin >> input; if (checkString(input)) { std::cout << "The string belongs to the grammar.\n"; } else { std::cout << "The string does not belong to the grammar.\n"; } return 0; }
Leave a Comment