leetcode 65 Valid Number

0 题目

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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

意思是,给定一个字符串判定该字符串是否是一个数字,不能有多余的字符。

注意的是跳过空格

1 分析

给定的字符串

  1. 跳过开头的结尾的空格
  2. 有效部分,记录e和.是否出现,如果已经出现过一次,那么下次出现的时候,就应该返回false
  3. 记录是否出现数字,当没出现数字的时候,e出现了,那么返回false,也就是第一位不能是e
  4. 如果出现了+ - ,那么,如果是在第一位,或是e后面的第一位是可以的,否则返回false
  5. 如果是s[i] 在‘0’,‘9’之间,那么表示是一个数字

最后返回的时候

  1. 有效部分结尾不能是e、+、-。(这里可以出现 .)
  2. 不能只有一个 .
bool isNumber(string s)
{
    int size = s.size();
    if (size == 0)
    {
        return false;
    }

    // 实际开始的标志,跳过头部的 0
    int start = 0;
    while (s[start] == ' ')
    {
        ++start;
    }

    // 实际结束的标志,跳过结尾的0
    int end = size - 1;
    while (s[end] == ' ')
    {
        --end;
    }

    // 处理实际的有效部分
    int hasNum = false, hasPoint = false, hasE = false;

    for (int i = start; i <= end; ++i)
    {
        if (s[i] == '.')
        {
            // 如果前面已经有了'.' 或者 'e'
            if (hasPoint || hasE)
            {
                return false;
            }
            hasPoint = true;
        }
        else if (s[i] == 'e')
        {
            // 前面已经出现字符e,或是前面没出现数字。
            if (hasE || !hasNum)
            {
                return false;
            }
            hasE = true;
        }
        else if (s[i] < '0' || s[i] > '9')
        {
            // 在开始的时候 + - 有效
            if (i == start && (s[i] == '+' || s[i] == '-'))
            {
                continue;
            }

            // 在e后面的+ - 有效
            else if ((i != 0 && s[i - 1] == 'e') && (s[i] == '+' || s[i] == '-'))
            {
                continue;
            }
            else
            {
                return false;
            }
        }
        else
        {
            hasNum = true;
        }
    }
    // 结尾不能是 e + -
    if (s[end] == 'e' || s[end] == '+' || s[end] == '-')
    {
        return false;
    }
    // 不能只有 .
    if (!hasNum && hasPoint)
    {
        return false;
    }
    return hasNum;
}

  

简单修改一下,可以变为,从字符串中提取数字。

原文地址:https://www.cnblogs.com/perfy576/p/8551944.html