Valid Number

mac2022-06-30  26

Description:

Validate if a given string is numeric.

Example

"0" => true" 0.1 " => true"abc" => false"1 a" => false"2e10" => true

Solution:

class Solution { public: /** * @param s the string that represents a number * @return whether the string is a valid number */ bool isNumber(string& s) { enum InputType { SPACE, // 0 SIGN, // 1 DIGIT, // 2 DOT, // 3 EXPONENT, // 4 TYPE_SIZE // 5 }; const int table[][TYPE_SIZE] = { 0, 3, 1, 2, -1, 8, -1, 1, 4, 5, -1, -1, 4, -1, -1, -1, -1, 1, 2, -1, 8, -1, 4, -1, 5, -1, 6, 7, -1, -1, -1, -1, 7, -1, -1, 8, -1, 7, -1, -1, 8, -1, -1, -1, -1, }; int state = 0; for (auto ch : s) { int inputType; if (ch == ' ' || ch == '\t') inputType = SPACE; else if (ch == '+' || ch == '-') inputType = SIGN; else if (ch >= '0' && ch <= '9') inputType = DIGIT; else if (ch == '.') inputType = DOT; else if (ch == 'e' || ch == 'E') inputType = EXPONENT; else return false; state = table[state][inputType]; if (state == -1) return false; } return state == 1 || state == 4 || state == 7 || state == 8; } };

转载于:https://www.cnblogs.com/deofly/p/valid-number.html

最新回复(0)