题目链接

  题目要求: 

  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. 【安卓开发】用PageTransformer打造更好的动画效果

    Android的ViewPager类已经变成一个相当流行的Android应用组件了.它简单直观,并且提供了极好的功能.你可以经常在设置向导,图片画廊种看到它,它还是分开应用内容的良好方式. 标准的Vi ...

  2. 关于Android PullTorefreshScrollview回到顶部实例

    列表滑动下面显示按钮,点击按钮回到顶部的功能,一般scrollview会有滑动监听的事件,通过setOnScrollChangeListener()滑动监听滑动的距离来判断是否显示按钮就好了,但是Pu ...

  3. Mac 下安装node.js

    Node.js 简介 Node.js 是一个用Chrome's V8 JavaScript engine 构建的 JavaScript 运行时框架.Node.js 使用事件驱动.非阻塞式 I/O 模块 ...

  4. linux中Cron定时任务系统命令详解

    分类:Linux VPS教程 作者:阿川 发布时间:October 13, 2011 有很多同学在购买VPS之后,需要用到计划任务.但是又对计划任务不太了解,所以.今天我们的帮助中心主要是给大家提供一 ...

  5. android自定义xmls文件属性

    在使用到自定义View的xml布局文件中需要加入xmlns:前缀=http://schemas.android.com/apk/res/你的自定义View所在的包路径. 下面是一个简单的例子: 结构图 ...

  6. ROS(indigo)ABB机器人MoveIt例子

    ROS(indigo)ABB机器人例子 参考网址: 1  http://wiki.ros.org/Industrial 2  http://wiki.ros.org/abb 3  https://gi ...

  7. UNIX网络编程——客户/服务器程序设计示范(二)

        TCP并发服务器程序,每个客户一个子进程 传统上并发服务器调用fork派生一个子进程来处理每个客户.这使得服务器能够同时为多个客户服务,每个进程一个客户.客户数目的唯一限制是操作系统对以其名义 ...

  8. (NO.00005)iOS实现炸弹人游戏(二):素材选择的取舍

    大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请告诉我,如果觉得不错请多多支持点赞.谢谢! hopy ;) 前面一篇里我们基本明确了游戏的大致玩法和特点.下面就游戏中会用到 ...

  9. Java中怎么简单的使用正则表达式?

    对于正则表达式,我通常的认识就是通过一些陌生的奇怪的符号就可以完成很复杂事件的好帮手!实际上正则表达式确实是这方面的好助手,接下来让我们一起认识一下Java中怎么使用正则表达式吧. 初见Pattern ...

  10. 基于WAMP的Crossbario 安装入门

    简单学习和使用WAMP协议,Router 是crossbario, Client是Autobahn, 了解运作的流程. 测试环境是Centos6 虚拟机一台 目录为 /data/wamp/ ,用的是P ...