ABC words: Difference between revisions

Content added Content deleted
(Added C++ solution)
m (Simplified C++ code)
Line 159: Line 159:


bool is_abc_word(const std::string& word) {
bool is_abc_word(const std::string& word) {
size_t a = std::string::npos;
bool a = false;
size_t b = std::string::npos;
bool b = false;
for (size_t pos = 0, n = word.size(); pos < n; ++pos) {
for (char ch : word) {
switch (word[pos]) {
switch (ch) {
case 'a':
case 'a':
// record position of first 'a'
if (!a)
if (a == std::string::npos)
a = true;
a = pos;
break;
break;
case 'b':
case 'b':
if (b == std::string::npos) {
if (!b) {
// fail if we haven't seen 'a' yet
// fail if we haven't seen 'a' yet
if (a == std::string::npos)
if (!a)
return false;
return false;
// record position of first 'b'
b = true;
b = pos;
}
}
break;
break;
case 'c':
case 'c':
// succeed iff we've seen 'b' already
// succeed iff we've seen 'b' already
return b != std::string::npos;
return b;
}
}
}
}