I have been practicing competitive coding for a while now and am using codeforces.com. I recently encountered a problem called "One Dimensional Japanese Crossword" on that site. The problem is as follows:
The judge provides an integer (up to 100) and then a string with that many characters being either 'B' or 'W'. We need to output how many groups of 'B' there are and how many 'B's there are in each group. For example:
Input:
6
BBWBWB
Output:
3
2 1 1
After lots of tries and lots of fails, I was finally able to get the code accepted by the judge. However, for some reason I feel that my code is really inefficient and there might be an easier and better way to solve this problem.
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int n;
cin >> n;
string s;
cin >> s;
int bGroups = 0;
int wGroups = 0;
char initChar = s[0];
for (int i = 1; i < s.length(); i++)
{
if (initChar == 'B')
{
if (s[i] != initChar)
{
bGroups++;
initChar = 'W';
}
}
else if (initChar == 'W')
{
if (s[i] != initChar)
{
wGroups++;
initChar = 'B';
}
}
}
if (s[n - 1] == 'B')
{
bGroups++;
}
else if (s[n - 1] == 'W')
{
wGroups++;
}
char init = s[0];
vector<int>grpSize(bGroups);
int counter = 0;
int i = 0;
while (counter < bGroups)
{
if (init == 'B')
{
while (init == 'B')
{
grpSize[counter]++;
i++;
init = s[i];
}
counter++;
while (init == 'W')
{
i++;
init = s[i];
}
}
else
{
while (init == 'W')
{
i++;
init = s[i];
}
while (init == 'B')
{
grpSize[counter]++;
i++;
init = s[i];
}
counter++;
}
}
cout << bGroups << endl;
for (int i = 0; i < bGroups; i++)
{
cout << grpSize[i] << " ";
}
}
So basically, in the first pass over the string, I count how many groups of 'B' and 'W' there are. Then I create an int vector to store the size of each 'B' group. Then on the second pass I fill in the values into the vector and then output the results.