题目链接

  题目要求: 

  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. Afianl加载网络图片(续)

    上一篇已经讲了如何利用Afianl加载网络图片和下载文件,这篇文章将继续讲解使用Afinal加载网络图片的使用,主要结合listview的使用: 看效果图: listview在滑动过程中没用明显卡顿, ...

  2. JAVA面向对象-----super关键字

    JAVA面向对象-–super关键字 1:定义Father(父类)类 1:成员变量int x=1; 2:构造方法无参的和有参的,有输出语句 2:定义Son类extends Father类 1:成员变量 ...

  3. JRE System Library [JavaSE-1.7](unbound)

    window > preferences > java > Install jars >如果没有jdk1.7 ,点击下面的search,会自动找到已经安装对jdk1.7,选择, ...

  4. Tomcat集群如何同步会话

    Tocmat集群中最重要的交换信息就是会话消息,对某个tomcat实例某会话做的更改要同步到集群其他tomcat实例的该会话对象,这样才能保证集群所有实例的会话数据一致.在tribes组件的基础上完成 ...

  5. 每个程序员都应该用MBP

    换笔记本的想法很久了,前段时间换工作就想看换工作之后是什么情况吧.可能工作配的笔记本就是MBP.后来发现是想多了,新工作的笔记本是Thinkpad X240, 配置完全够用了,8G内存+128G的FL ...

  6. C语言--static修饰变量

    Static在C语言里面有两个作用,第一个是修饰变量,第二个是修饰函数. 1.Static修饰变量 按照作用范围的不同,变量分为局部变量和全局变量.如果用static修饰变量,不论这个变量是全局的还是 ...

  7. div效果很好的遮盖层效果

    [html] view plaincopyprint? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN&qu ...

  8. SDL2源代码分析6:复制到渲染器(SDL_RenderCopy())

    ===================================================== SDL源代码分析系列文章列表: SDL2源代码分析1:初始化(SDL_Init()) SDL ...

  9. Mysql group by语句的优化

    默认情况下,MySQL排序所有GROUP BY col1, col2, ....,查询的方法如同在查询中指定ORDER BY  col1, col2, ....如果显式包括一个包含相同的列的ORDER ...

  10. iOS积分抽奖Demo,可以人为控制不同奖项的得奖率

    最近公司让写一个转盘积分抽奖的样式,所以把创建过程中的心得记录一下,给大家分享 首先创建了相关的图片转盘,指针图片,然后就是考虑转盘如何旋转的问题,我是通过给指针图片添加一个动画效果,从而实现旋转效果 ...