解題思路
將關鍵字與欄位名轉小寫,辨識SELECT、1至5個欄位、WHERE、條件欄位、>與一個整數。
欄位清單只接受空白分隔或逗號分隔且不可有空欄;name不能作數值條件。任何格式錯誤輸出ERROR。
語法正確後逐筆掃描題目固定的五筆資料,以嚴格大於篩選並依指定欄位次序投影,資料及欄位重複均保留。
時間 O(L)解析加固定5筆投影;空間 O(L)。數值門檻使用任意精度。
Step-by-step animation
教學小例:限制文法的固定資料庫查詢
步驟 1 / 3
查詢name WHERE no>3
先確認name與no皆為合法欄位
先確認name與no皆為合法欄位
- 步驟
- 1
#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
int main() {
string s;
getline(cin, s);
for (char &c : s)
c = tolower(c);
smatch m;
regex re(
R"(^\s*select\s+(.+?)\s+where\s+(no|chinese|english|history)\s*>\s*([+-]?[0-9]+)\s*$)");
if (!regex_match(s, m, re)) {
cout << "ERROR\n";
return 0;
}
map<string, int> id = {
{"no", 0}, {"name", 1}, {"chinese", 2}, {"english", 3}, {"history", 4}};
string fields = m[1];
vector<int> cols;
bool ok = true;
if (fields.find(',') != string::npos) {
stringstream ss(fields);
string p;
if (fields.back() == ',')
ok = false;
while (getline(ss, p, ',')) {
stringstream t(p);
string a, b;
t >> a;
if (!id.count(a) || (t >> b))
ok = false;
else
cols.push_back(id[a]);
}
} else {
stringstream ss(fields);
string p;
while (ss >> p) {
if (!id.count(p))
ok = false;
else
cols.push_back(id[p]);
}
}
if (!ok || cols.empty() || cols.size() > 5) {
cout << "ERROR\n";
return 0;
}
string z = m[3];
bool neg = z[0] == '-';
cpp_int limit = 0;
for (char c : z)
if (isdigit(c))
limit = limit * 10 + c - '0';
if (neg)
limit = -limit;
vector<vector<string>> db = {{"1", "Eric", "96", "88", "91"},
{"2", "Mary", "77", "66", "49"},
{"3", "Jack", "50", "33", "100"},
{"4", "Chris", "69", "97", "87"},
{"5", "Robin", "72", "55", "67"}};
for (auto &r : db)
if (cpp_int(r[id[m[2]]]) > limit) {
for (int i = 0; i < (int)cols.size(); i++) {
if (i)
cout << ' ';
cout << r[cols[i]];
}
cout << '\n';
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。