Skip to content

Instantly share code, notes, and snippets.

@kanrourou
Created December 28, 2018 20:26
Show Gist options
  • Save kanrourou/5b87a2dd5c8b82597b712861735941d2 to your computer and use it in GitHub Desktop.
Save kanrourou/5b87a2dd5c8b82597b712861735941d2 to your computer and use it in GitHub Desktop.
class Solution {
public:
bool isNumber(string s) {
vector<vector<int>> transferTable = {
{1, 2, 3, -1, -1},
{-1, 2, 3, -1, -1},
{-1, 2, 4, 5, -1},
{-1, 4, -1, -1, -1},
{-1, 4, -1, 5, -1},
{6, 7, -1, -1, -1},
{-1, 7, -1, -1, -1},
{-1, 7, -1, -1, -1}
};
int state = 0, len = s.size(), i = 0, j = len - 1;
while(i < len && s[i] == ' ')++i;
while(j >= 0 && s[j] == ' ')--j;
if(j < i)return false;
for(int k = i; k <= j; ++k)
{
int input = getInput(s[k]);
state = transferTable[state][input];
if(state == -1)return false;
}
return state == 2 || state == 4 || state == 7;
}
private:
int getInput(char c)
{
switch(c)
{
case '+':
case '-':
return 0;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return 1;
case '.':
return 2;
case 'e':
return 3;
default:
return 4;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment