[LeetCode-Algorithms-65] "Valid Number" (2017.11.1-WEEK9)

来源:互联网 发布:淘宝买家秀点赞 编辑:程序博客网 时间:2024/05/19 09:40

题目链接: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.

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)思路:判断一个字符串是不是数字。

a.排除首尾空格b.排除头部符号位c.剩下的字符串再进行检查。    在碰到e之前,判断字符是否是 0-9 的数字或小数点。要注意.1 和1. 这种格式都是可以被判断为数字的。    碰到指数之后,后面不能有小数点,指数后面第一位可以是符号位,其余只能是数字。

(2)代码:

class Solution {public:    bool isNumber(string s) {      auto realStart = s.find_first_not_of(' ');      auto realEnd = s.find_last_not_of(' ');      int num_count = 0, exp_count = 0, point_count = 0;      bool exp_flag = false;      if (s[realStart] == '+' || s[realStart] == '-') realStart++;      for (auto i = realStart; i <= realEnd; i++) {        if (exp_flag) {          if (exp_count == 0 && num_count == 0 && (s[i] == '+' || s[i] == '-')) exp_count = 1;          else if (s[i] <= '9' && s[i] >= '0') num_count++;          else return false;        }         else {          if (s[i] == 'e') {            if (num_count == 0) return false;            exp_flag = true;            num_count = 0;          }          else if (s[i] <= '9' && s[i] >= '0') num_count++;          else if (s[i] == '.') point_count++;           else return false;            }      }      if (num_count < 1 || point_count > 1) return false;      return true;    }};

(3)提交结果:

这里写图片描述