LeetCode之“字符串”: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.
这道题看起来貌似简单,实则要考虑的情况非常多。更可惜的是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(由此引发的对正则表达式的学习)的更多相关文章
- 【LeetCode】65. Valid Number
Difficulty: Hard More:[目录]LeetCode Java实现 Description Validate if a given string can be interpreted ...
- LeetCode OJ:Valid Number
Validate if a given string is numeric. Some examples:"0" => true" 0.1 " => ...
- 【一天一道LeetCode】#65. Valid Number
一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Validat ...
- 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 ...
- 【leetcode】Valid Number
Valid Number Validate if a given string is numeric. Some examples:"0" => true" 0.1 ...
- [leetcode]65. Valid Number 有效数值
Validate if a given string can be interpreted as a decimal number. Some examples:"0" => ...
- LeetCode: Valid Number 解题报告
Valid NumberValidate if a given string is numeric. Some examples:"0" => true" 0.1 ...
- leetCode 65.Valid Number (有效数字)
Valid Number Validate if a given string is numeric. Some examples: "0" => true " ...
- [Swift]LeetCode65. 有效数字 | Valid Number
Validate if a given string is numeric. Some examples:"0" => true" 0.1 " => ...
随机推荐
- Eclipse编写ExtJS卡死问题 eclise js验证取消
1. Eclipse编写ExtJS卡死问题 eclise js验证取消 近期项目用到了extjs,发现项目编译的时候特别的卡,浪费很多时间而且保存的时候还要编译,因此打算看下如何取消验证extjs.最 ...
- Retrofit 2.0 超能实践(三),轻松实现文件/多图片上传/Json字符串
文:http://blog.csdn.net/sk719887916/article/details/51755427 Tamic 简书&csdn同步 通过前两篇姿势的入门 Retrofit ...
- XML之DTD(文档类型定义)
文档类型定义(DTD)可定义合法的XML文档构建模块.它使用一系列合法的元素来定义文档的结构. DTD 可被成行地声明于 XML 文档中,也可作为一个外部引用. 声明元素 在 DTD 中,XML 元素 ...
- Android初级教程对大量数据的做分页处理理论知识
有时候要加载的数据上千条时,页面加载数据就会很慢(数据加载也属于耗时操作).因此就要考虑分页甚至分批显示.先介绍一些分页的理论知识.对于具体用在哪里,会在后续博客中更新. 分页信息 1,一共多少条数据 ...
- 网站开发进阶(四十二)巧用clear:both
网站开发进阶(四十二)巧用clear:both 前言 我们在制作网页中用div+css或者称xhtml+css都会遇到一些很诡异的情况,明明布局正确,但是整个画面却混乱起来了,有时候在IE6下看的很正 ...
- 怎么对MySQL数据库操作大数据?这里有思路
最近学到一招关于使用java代码操作MySQL数据库,对大文本数据(LOB)进行CRUD的技巧,虽然向数据库很少向中存入大文本文件(一般都是存储在硬盘上),但是还是很有必要知道这一技巧的.下面我就来说 ...
- [GitHub]第一讲:浏览器中使用GitHub
文章转载自http://blog.csdn.net/loadsong/article/details/51591407 看到一篇关于GitHub的文章,感觉不错,因此转载来以备推敲学习. 不会用 Gi ...
- mac 下终端 操作svn命令 以及出现证书错误的处理方法
首先,转载地址:http://hi.baidu.com/zhu410289616/item/eaaf160f60eb0dc62f4c6b0e 还有一个地址:http://www.cnblogs.com ...
- Sprite添加阴影摇摆动画(Unity3D开发之九)
猴子原创,欢迎转载.转载请注明: 转载自Cocos2D开发网–Cocos2Dev.com,谢谢! 原文地址: http://www.cocos2dev.com/?p=575 今天看到一个很简单的摇摆动 ...
- iOS中 Animation 动画大全 韩俊强的博客
每日更新关注:http://weibo.com/hanjunqiang 新浪微博! iOS开发者交流QQ群: 446310206 1.iOS中我们能看到的控件都是UIView的子类,比如UIButt ...