您的位置:首页 > 其它

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

2015-06-05 22:09 429 查看
  题目链接

  题目要求: 

  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库提供的正则表达式。

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

class Solution {
public:
bool isValidChar(char c)
{
string str = "0123456789.e+-";
return str.find(c) != -1;
}

bool isDigit(int in)
{
char ref[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
for (int i = 0; i < 10; i++)
{
if (in == ref[i])
return true;
}
return false;
}

bool isNumber(string s) {
// clear spaces
while (s.begin() != s.end() && s.front() == ' ')
s.erase(0, 1);
while (s.begin() != s.end() && s.back() == ' ')
s.pop_back();

int szS = s.size();
if (szS == 0)
return false;
// only '.'
if (szS == 1 && s[0] == '.')
return false;
// 'e' at the first or last position of s
if (s[0] == 'e' || s[szS - 1] == 'e')
return false;
// too many signs
if (szS > 1 && (s[0] == '-' || s[0] == '+') && (s[1] == '-' || s[1] == '+'))
return false;
// sign at the last
if (s[szS - 1] == '+' || s[szS - 1] == '-')
return false;

szS = s.size();
int countDot = 0;
int countE = 0;
for (int i = 0; i < szS; i++)
{
if (!isValidChar(s[i]))
return false;

if (s[i] == '.') //'.e at the begining, ' '.+/-' are not allowed
{
countDot++;
if (i + 1 < szS && ((i == 0 && s[i + 1] == 'e') || s[i + 1] == '+' || s[i + 1] == '-'))    // '.e'
return false;
}
if (s[i] == 'e') // 'e.' 'e+/-...+/-' are not allowed
{
countE++;
if (i + 1 < szS)
{
int pos1 = s.find('.', i + 1);
if (pos1 != -1)
return false;
}
if (i + 2 < szS)
{
int pos2 = s.find('+', i + 2);
int pos3 = s.find('-', i + 2);
if (pos2 > (i + 1) || pos3 > (i + 1))
return false;
}
}
if (s[i] == '+') // '+e' '+-' 'digit+/' are not allowed
{
if (i + 1 < szS && (s[i + 1] == 'e' || s[i + 1] == '-'))
return false;
if (i > 0 && isDigit(s[i - 1]))
return false;
}
if (s[i] == '-') // '. at the last' '-e' '-+' 'digit+/' are not allowed
{
if (i + 1 < szS && ((i + 1 == szS - 1 && s[i + 1] == '.') || s[i + 1] == 'e' || s[i + 1] == '+'))
return false;
if (i > 0 && isDigit(s[i - 1]))
return false;
}

if (countDot > 1 || countE > 1) // no double dots or double e can exit
return false;

}

return true;
}
};


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: