题目链接

  题目要求: 

  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. Android必知必会-获取View坐标和长宽的时机

    如果移动端访问不佳,请访问–>Github版 背景 最近要实现一个功能,用到了一些属性动画,需要获取一些View的坐标信息,设计图如下: 这里我使用的是DialogFragment来实现的,可以 ...

  2. Android初级教程:如何自定义一个状态选择器

    有这样一种场景:点击一下某个按钮或者图片(view),改变了样式(一般改变背景颜色).这个时候一种解决方案,可能就是状态选择器.接下来就介绍如何实现状态选择器: 步骤: 一.新建这样的文件夹:res/ ...

  3. UE4成批处理透明材质

    项目中需要控制成批的物体的透明度,但是默认的时候他又不能是透明的,对,项目的要求就这么诡异. 然而却没有找到设置材质的BlendMode的功能,于是只有换了一种办法,物体需要透明时更换为透明材质,默认 ...

  4. Android初级教程:单击事件的传递机制初谈

    以上仅是小试牛刀,后续有很多事件传递机制,继续探讨.

  5. 07 总结ProgressDialog 异步任务

    1,ProgressDialog     >        //使用对象  设置标题             progressDialog.setTitle("标题");   ...

  6. HashMap方法介绍

    1. Map的遍历方式 (1) for each map.entrySet() Map<String, String> map = new HashMap<String, Strin ...

  7. java wait和notify及 synchronized sleep 总结

    java 中线程我一直弄不清线程锁等 所以写了一些例子验证看法: 在这之前先看下API中wait中的解释: wait:方法来之java.lang.Objetc 方法翻译:在其他线程调用此对象的 not ...

  8. findbugs, checkstyle, pmd的myeclipse7.5+插件安装(转:http://blog.csdn.net/priestmoon/article/details/63941)

    CheckStyle (1)下载net.sf.eclipsecs_5.3.0.201012121300-updatesite-.zip (2)打开MyEclipse,Help->Software ...

  9. Windows7 x64 跨平台开发环境安装配置

    ======================================================================= Windows7 x64 跨平台开发环境安装配置 201 ...

  10. Android用AlarmManager实现后台任务-android学习之旅(63)

    因为Timer不能唤醒cpu,所以会在省电的原因下失效,所以需要唤醒cpu在后台稳定化的执行任务,AlarmManager能够唤醒cpu 这个例子讲解了如何通过Service来在后他每一个小时执行.特 ...