zoukankan      html  css  js  c++  java
  • Valid Number

    Validate if a given string is numeric.
    Some examples:
    "0" => true
    " 0.1 " => true
    "abc" => false
    "1 a" => false
    "2e10" => true
    Note: It is intended for the problem statement to be ambiguous. You should gather all
    requirements up front before implementing one.

    Solution: This finite-state machine solution. Learn from fuwutu & snakeDling.

     1 class Solution {
     2 public:
     3     bool isNumber(const char *s) {
     4         enum InputType {INVALID, SPACE, SIGN, DIGIT, DOT, EXPONENT};
     5         int transitionTable[][6] = 
     6         { /* 0   1   2   3   4   5  */
     7              0,  1,  2,  3,  4,  0, // 0: INVALID
     8              0,  1,  2,  3,  4,  0, // 1: SPACE
     9              0,  0,  0,  3,  4,  0, // 2: SIGN
    10              0,  6,  0,  3,  7,  5, // 3: DIGIT
    11              0,  0,  0,  7,  0,  0, // 4: DOT
    12              0,  0,  2,  8,  0,  0, // 5: EXPONENT
    13              0,  6,  0,  0,  0,  0, // 6: END WITH SPACE
    14              0,  6,  0,  7,  0,  5, // 7: DOT AND DIGIT
    15              0,  6,  0,  8,  0,  0, // 8: END WITH SPACE OR DIGIT
    16         };
    17         
    18         InputType last = INVALID;
    19         while (*s != '')
    20         {
    21             InputType state = INVALID;
    22             if (*s == ' ')
    23                 state = SPACE;
    24             else if (isdigit(*s))
    25                 state = DIGIT;
    26             else if (*s == '+' || *s == '-')
    27                 state = SIGN;
    28             else if (*s == 'e')
    29                 state = EXPONENT;
    30             else if (*s == '.')
    31                 state = DOT;
    32             last = (InputType) transitionTable[last][state];
    33             if (last == INVALID) return false;
    34             s++;
    35         }
    36         bool validFinal[] = {0, 0, 0, 1, 0, 0, 1, 1, 1};
    37         return validFinal[last];
    38     }
    39 };
  • 相关阅读:
    r语言
    pickle模块
    mongodb简介
    oracle
    mysql
    ceph
    迭代器
    python类
    encode&decode
    PHP 截取字符串中某两个字符(串)之间的字符串 考虑多个的情况
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3679641.html
Copyright © 2011-2022 走看看