题目链接

  题目要求: 

  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.

  这道题看起来貌似简单,实则要考虑的情况非常多。更可惜的是LeetCode并不支持正则表达式。。。。下文先试着以正则表达式的方法去解决这个问题。

  C++现在是提供了对正则表达式的支持的,但貌似用的少,更多的是Boost库提供的正则表达式。

  法一和法二的测试用例来自一博文,且这两个方法均测试通过。测试用例可从百度云下载得到。另外,具体的文件读写及函数验证程序如下:

 #include <fstream>
... ...
ifstream in("C:\\Users\\xiehongfeng100\\Desktop\\LeetCode_Valid_Number_Test_Cases.txt");
if (in) // if file exists
{
string line;
while (getline(in, line)) // read each line from 'in'
{
string input;
bool expect; // extract 'input'
line.erase(, );
int tmpFind = line.find('"');
input = line.substr(, tmpFind);
while (input.begin() != input.end() && input.front() == ' ')
input.erase(input.begin());
while (input.begin() != input.end() && input.back() == ' ')
input.pop_back(); // extract 'expect'
string expectStr = line.substr(tmpFind + , line.size() - line.find('\t', tmpFind + ) - );
if (expectStr == "TRUE")
expect = true;
else
expect = false; // validate
bool isValid = isNumber(input);
if (isValid != expect)
cout << "Something wrong! " << line << endl;
}
}
else
{
cout << "No such file" << endl;
}

  1. 法一:基于C++自身正则表达式

  用正则表达式写出来的程序非常简洁:

 #include <regex>
... ...
bool isNumber(string buf)
{
regex pattern("[+-]?(\\.[0-9]+|[0-9]+\\.?)[0-9]*(e[+-]?[0-9]+)?", regex_constants::extended);
match_results<string::const_iterator> result;
return regex_match(buf, result, pattern);
}

  2. 法二:基于Boost库正则表达式

  Boost库的正则表达式的语法跟C++自身提供的有点差别。Boost库的跟其他语言更加兼容。

 #include <boost/regex.hpp>
... ...
bool isNumber(string buf)
{
string Reg = "[+-]?(\\.\\d+|\\d+\\.?)\\d*(e[+-]?\\d+)?";
boost::regex reg(Reg);
return boost::regex_match(buf, reg);
}

  3. 法三:列举所有情况

  这种方法很繁杂。。。

 class Solution {
public:
bool isValidChar(char c)
{
string str = "0123456789.e+-";
return str.find(c) != -;
} bool isDigit(int in)
{
char ref[] = { '', '', '', '', '', '', '', '', '', '' };
for (int i = ; i < ; i++)
{
if (in == ref[i])
return true;
}
return false;
} bool isNumber(string s) {
// clear spaces
while (s.begin() != s.end() && s.front() == ' ')
s.erase(, );
while (s.begin() != s.end() && s.back() == ' ')
s.pop_back(); int szS = s.size();
if (szS == )
return false;
// only '.'
if (szS == && s[] == '.')
return false;
// 'e' at the first or last position of s
if (s[] == 'e' || s[szS - ] == 'e')
return false;
// too many signs
if (szS > && (s[] == '-' || s[] == '+') && (s[] == '-' || s[] == '+'))
return false;
// sign at the last
if (s[szS - ] == '+' || s[szS - ] == '-')
return false; szS = s.size();
int countDot = ;
int countE = ;
for (int i = ; i < szS; i++)
{
if (!isValidChar(s[i]))
return false; if (s[i] == '.') //'.e at the begining, ' '.+/-' are not allowed
{
countDot++;
if (i + < szS && ((i == && s[i + ] == 'e') || s[i + ] == '+' || s[i + ] == '-')) // '.e'
return false;
}
if (s[i] == 'e') // 'e.' 'e+/-...+/-' are not allowed
{
countE++;
if (i + < szS)
{
int pos1 = s.find('.', i + );
if (pos1 != -)
return false;
}
if (i + < szS)
{
int pos2 = s.find('+', i + );
int pos3 = s.find('-', i + );
if (pos2 > (i + ) || pos3 > (i + ))
return false;
}
}
if (s[i] == '+') // '+e' '+-' 'digit+/' are not allowed
{
if (i + < szS && (s[i + ] == 'e' || s[i + ] == '-'))
return false;
if (i > && isDigit(s[i - ]))
return false;
}
if (s[i] == '-') // '. at the last' '-e' '-+' 'digit+/' are not allowed
{
if (i + < szS && ((i + == szS - && s[i + ] == '.') || s[i + ] == 'e' || s[i + ] == '+'))
return false;
if (i > && isDigit(s[i - ]))
return false;
} if (countDot > || countE > ) // no double dots or double e can exit
return false; } return true;
}
};

LeetCode之“字符串”:Valid Number(由此引发的对正则表达式的学习)的更多相关文章

  1. 【LeetCode】65. Valid Number

    Difficulty: Hard  More:[目录]LeetCode Java实现 Description Validate if a given string can be interpreted ...

  2. LeetCode OJ:Valid Number

    Validate if a given string is numeric. Some examples:"0" => true" 0.1 " => ...

  3. 【一天一道LeetCode】#65. Valid Number

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Validat ...

  4. 74th LeetCode Weekly Contest Valid Number of Matching Subsequences

    Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of ...

  5. 【leetcode】Valid Number

    Valid Number Validate if a given string is numeric. Some examples:"0" => true" 0.1 ...

  6. [leetcode]65. Valid Number 有效数值

    Validate if a given string can be interpreted as a decimal number. Some examples:"0" => ...

  7. LeetCode: Valid Number 解题报告

    Valid NumberValidate if a given string is numeric. Some examples:"0" => true" 0.1 ...

  8. leetCode 65.Valid Number (有效数字)

    Valid Number  Validate if a given string is numeric. Some examples: "0" => true " ...

  9. [Swift]LeetCode65. 有效数字 | Valid Number

    Validate if a given string is numeric. Some examples:"0" => true" 0.1 " => ...

随机推荐

  1. 给定一个实数数组,按序排列(从小到大),从数组从找出若干个数,使得这若干个数的和与M最为接近,描述一个算法,并给出算法的复杂度。

    有N个正实数(注意是实数,大小升序排列) x1 , x2 ... xN,另有一个实数M. 需要选出若干个x,使这几个x的和与 M 最接近. 请描述实现算法,并指出算法复杂度. #define M 8 ...

  2. 关于JQuery中的ajax请求或者post请求的回调方法中的操作执行或者变量修改没反映的问题

    前段时间做一个项目,而项目中所有的请求都要用jquery 中的ajax请求或者post请求,但是开始处理一些简单操作还好,但是自己写了一些验证就出现问题了,比如表单提交的时候,要验证帐号的唯一性,所以 ...

  3. char能表示(-128~127)

    char 的取值范围是 -128 ~127 注:数0的补码表示是唯一的: +0的补码=+0的反码=+0的原码=00000000 -0的补码=11111111+1=00000000(mod 2的8次方) ...

  4. spring @Qualifier注解使用

    @Autowired是根据类型进行自动装配的.如果当Spring上下文中存在多个UserDao类型的bean时,就会抛出BeanCreationException异常;如果Spring上下文中不存在U ...

  5. 06_MyBatis,Spring,SpringMVC整合

     项目结构 Spring的配置: beans.xml <?xml version="1.0" encoding="UTF-8"?> <be ...

  6. 运用 三种 原生 谷歌 阿里 解析和生成json

    三种类生成JSON数据方法 JSON(原生): 第一种 JSONStringer和JSONObject区别在于添加对象时是按顺序添加的比如说 JSONStringer 添加 a:1 b:2 c:3那么 ...

  7. 06_NoSQL数据库之Redis数据库:Redis的高级应用之登录授权和主从复制

     Redis高级实用特征 安全性(登录授权和登录后使用auth授权) 设置客户端连接后进行任何其他指定前需要使用的密码. 警告:因为redis速度相当快,所以在一台比较好的服务器下,一个外部的用户 ...

  8. Arquillian Exception:java.lang.NoClassDefFoundError

    Issue: When you deploy and run Arquillian testcase, you may encountered java.lang.NoClassDefFoundErr ...

  9. [C++学习历程]Visual Studio 2010 中文旗舰版 安装

    作者: 苏生米沿 本文地址:http://blog.csdn.net/sushengmiyan/article/details/19765441 要开始学习C++了,先装个开发环境吧,没有选择最新的2 ...

  10. iOS中类单例方法的一种实现

    在Cocos2D编程中,很多情况我们需要类只生成一个实例,这称之为该类的单例类. 一般我们在类中这样实现单例方法: +(instancetype)sharedInstance{ static Foo ...