1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
|
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::string;
bool isWellFormedAirportString(std::string s);
int main()
{
std::vector<string> v {"aa1+1", "aa132-124", "aa142-3",
"ua32-0", "sw-231", "a1-1",
"aa-3-333", "aa4*324", "aa1111-1"};
for(auto test : v) {
cout << "isWellFormedAirportString(\"" << test
<< "\") returned "
<< isWellFormedAirportString(test) << endl;
}
return 0;
}
/* =================================================================
* Valid codes:
* 2 alphabets: airlinecode
* + digits 0 to 999: flight number
* (+ or -) digit 0 to 999: arrival minute different than
* the scheduled time
* valid form: aa1+1, aa132-124, aa142-3ua32-0sw-231
* invalid form: a1-1, aa-3-333, aa4*324, aa1111-1
* ================================================================= */
bool isWellFormedAirportString(std::string s) {
// There can't be less then
// 2 letters (airline code)
// + 1 digit (flight number)
// + 1 character between + or -
// + 1 digit (minutes of differences)
// 5 characters in s.
if(s.size() < 5)
return false;
// Let's check if first 2 characters are 2 letters
if (!isalpha(s.at(0)) || !isalpha(s.at(1))) {
return false;
} else {
// We don't need the first 2 characters any more.
// (let's keep things simple) :-)
// Note: could also be written s.erase(2), since the first
// parameter default to 0.
s.erase(0, 2);
}
// Let's search for a '+' or a '-' now.
string::size_type plusminus(string::npos);
if( (plusminus=s.find_first_of("+-")) != string::npos ) {
// Ok, somewhere there is a '+' or a '-', but it must
// not be beyond the 3rd character.
// Let's assume now s starts with 3 digits, in positions
// 0, 1, 2. plusminus should not be > 3.
if(plusminus > 3) {
return false;
} else {
// Now we need to check if in s[0] to s[plusminus -1]
// there are digits.
for(string::size_type i(0); i < plusminus -1; i++) {
if(!isdigit(s.at(i)))
return false;
}
}
} else {
// We get here if find_first_of returns npos, that means
// there isn't neither a '+' nor a '-' in s,
// so s is invalid.
return false;
}
// If we get here, we know that now s starts with 1, 2 or 3
// digits followed by a '+' or a '-'.
// The position of the '+' or the '-' is stored in plusminus.
// We don't need any of them any more.
s.erase(plusminus); // ...or s.erase(0, plusminus);
// Ok, now we must check if there is any character left
// (the '+' or the '-' could have not be followed by
// any other character) end if they are digits.
if(s.empty())
return false;
for(string::size_type i(0); i < s.size(); i++) {
if(!isdigit(s.at(i)))
return false;
}
// Wow! We get to the end...
// We can safely infer that s is valid.
return true;
}
|