#include <iostream> #include <string> #include <map> using namespace std; enum State { START, HAS_A, ONLY_B, END }; bool DFA(string s) { int state = START; map<State, map<char, State>> transition = { {START, {{'a', HAS_A}}}, {HAS_A, {{'a', END}, {'b', ONLY_B}}}, {ONLY_B, {{'a', HAS_A}, {'b', ONLY_B}}}, {END, {}} }; for (int i = 0; i < s.size(); i++) { if (transition[state].find(s[i]) == transition[state].end()) return false; state = transition[state][s[i]]; } return state == END;} int main() { string s; cin >> s; if (DFA(s)) { cout << "Accept" << endl; } else { cout << "Error" << endl; } return 0; }优化这段代码
时间: 2024-01-30 20:03:12 浏览: 59
#include <iostream>
这段代码的 DFA 实现比较简洁,已经使用了状态转移表,但是可以在细节上进行一些优化,比如使用 const、引用等:
```cpp
#include <iostream>
#include <string>
#include <unordered_map>
enum class State {
START,
HAS_A,
ONLY_B,
END
};
bool DFA(const std::string& s) {
State state = State::START;
const std::unordered_map<State, std::unordered_map<char, State>> transition = {
{State::START, {{'a', State::HAS_A}}},
{State::HAS_A, {{'a', State::END}, {'b', State::ONLY_B}}},
{State::ONLY_B, {{'a', State::HAS_A}, {'b', State::ONLY_B}}},
{State::END, {}}
};
for (const char& c : s) {
if (transition.find(state) == transition.end() || transition.at(state).find(c) == transition.at(state).end()) {
return false;
}
state = transition.at(state).at(c);
}
return state == State::END;
}
int main() {
std::string s;
std::cin >> s;
if (DFA(s)) {
std::cout << "Accept" << std::endl;
} else {
std::cout << "Error" << std::endl;
}
return 0;
}
```
主要的改进有:
1. 使用 `enum class` 代替 `enum`,避免命名空间污染
2. 使用 `std::unordered_map` 代替 `std::map`,提高查找效率
3. 使用 const、引用等来提高代码的安全性和效率
阅读全文