Leetcode_65 Valid Number

来源:互联网 发布:linux读取文件指定行 编辑:程序博客网 时间:2024/06/15 13:32
忽然想起又有一周没写博客了,今天没做其它的,就做了一道题,就写写这道题吧。题目:Validate if a given string is numeric.Some examples:"0" => true" 0.1 " => true"abc" => false"1 a" => false"2e10" => trueNote: 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次,其前面能够没有数字,但后面一定要有数字;对于'e':最多仅仅可以出现1次,其前后都必须有数字。但后面一定是整数,即不能出现'.';对于'+'和'-':'e'的前后都最多可以出现1次,且一定要在数字最前面出现;至于其它字符。只能是数字(0~9)。代码(有点笨的方法实现的,debug了好久):
bool leetcode_65_isnumber(char a){ if (a >= '0'&&a <= '9') { return true; } return false;}bool Leetcode_65::isNumber(string s){ int dianflag = 0, dian_num_begin_flag = 0, dian_num_end_flag = 0; //.的标志位 int eflag = 0, e_num_begin_flag = 0, e_num_end_flag = 0; //e的标志位 int jia_flag = 0, jian_flag = 0; //加号和减号的标志位 int shuzi_flag = 0, e_shuzi_flag = 0; //第一个标志位表示前面出现了空格再出现数字,第二个标志位表示先出现数字再出现空格 int after_e_flag = 0; int length = s.size(); for (int i = 0; i < length; ++i) { if (s[i] == '.') { if (dianflag == 1) { return false; } if (eflag == 1) { return false; } dianflag = 1; } else if (s[i] == 'e') { if (eflag == 1) { return false; } if (shuzi_flag == 0) { return false; } if (i == length - 1) { return false; } eflag = 1; } else if (s[i] == '+' || s[i] == '-') { if (dianflag == 1) { if (i >= 1 && s[i - 1] == 'e') { } else { return false; } } if (shuzi_flag == 0) { if (jia_flag == 1) { return false; } jia_flag = 1; continue; } else if (eflag == 1 && e_shuzi_flag == 0) { jia_flag = 1; continue; } else { return false; } } else if (s[i] == ' ') { if ((jia_flag == 1 || jian_flag == 1) && (shuzi_flag == 0)) { return false; } if (shuzi_flag == 1 || dianflag == 1) { while (s[i] == ' ') { ++i; if (i == length) { if (shuzi_flag == 0) { return false; } if (eflag == 1 && e_shuzi_flag == 0) { return false; } return true; } } return false; } else { continue; } } else if (leetcode_65_isnumber(s[i])) { if (dianflag == 0) { dian_num_begin_flag = 1; } else { dian_num_end_flag = 1; } if (eflag == 0) { e_num_begin_flag = 1; } else { e_num_end_flag = 1; } if (eflag == 1) { e_shuzi_flag = 1; } else { shuzi_flag = 1; } } else { return false; } } if (shuzi_flag == 0) { return false; } if (eflag == 1 && e_shuzi_flag == 0) { return false; } return true;}
运行时间:
查看原文:http://www.xuchenbjtu.cn/index.php/2017/12/08/leetcode_65-valid-number/
原创粉丝点击