One common techinque to solve these kind of problems is to write a state machine.
In our case, the state machine is:
Instead of writng the state machine a one big function with a lot of state and a bunch of "if" statements, we're going to write states as functions.
To simplify things, the end state is going to be nil for easy comparison.
Then our main function will look like:
An here's how startState looks like
When you write this style of code, states are small and contained function. Easier to test and reason about.
Final comments:
- You can see the full code here
- This blog was inspired by the Valid Number problem on leetcode
- Rob Pike has an excellent "Lexcical Scanning in Go" talk that demonstrates this methon
No comments:
Post a Comment