I have a string S consisting of N letters 'a' or 'b'. This should return true when all occurrences of 'a' are before all occurrences of 'b' and return false otherwise.
b does not need to occur in S and a does not need to occur in S
For example
S='aabbb' returns true
S = 'ba' returns false
S = 'aaa' returns true
S= 'b' returns true
S='abba' returns false
this is my solution but it displays 1 extra true. I don't know why.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector <string> vec;
int n;
string item;
int contora=0,contorb=0;
cout<<"n: ";
cin>>n;
cout << "Enter a string: ";
for(int i=0;i<= n;i++){
getline(cin, item);
//cin>>item;
vec.push_back(item);
}
for (int j=0; j <= n; j++) {
cout << vec[j];
}
cout<<endl;
for (auto of:vec) {
if (of.find("ba") != std::string::npos)
cout << "false";
else
cout<<"true";
}
return 0;
}
Adding some debug output to the code shows a couple of issues:
forloop reads inn+1strings, while we are expecting the user to enter onlynstrings. The secondforloop also printsn+1strings, although that's not a problem, because the vector containsn+1elements.std::cin >>andstd::getlinefor reading user input, the first string read withstd::getlineis empty. You would need whether to:std::getlinefor all the user input readings (and, forn, convert the string to a number), orcin.ignoreafter thestd::cin >>, as explained in this answer.The code below fixes those two issues and adds some debug output (it also follows a few best practices such as, not
using namespace std;, defining variables next to their first use, value-initializing local variables, and using block braces even for one-line blocks).[Demo]
For this particular case, you could also use
std::is_partitioned. This algorithm tells you if all the elements of a range that satisfy a given predicate appear before all the elements that don't (see here). The predicate would check if a character is equal to'a'.[Demo]