Tuesday, September 17, 2013

valid number@leetcode

刷题必备书籍Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
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.

这道题和string to integer有相似之处。主要就是各类情况都要考虑清楚。有人用finite automata 去做。我还是偏向于直接写代码。有一个地方卡了好久不过,也不晓得为什么。

class Solution {
public:
bool isNumber(const char *s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (s == NULL)
return false;
while(isspace(*s))
s++;
if (*s == '+' || *s == '-')
s++;
bool eAppear = false;
bool dotAppear = false;
bool firstPart = false;
bool secondPart = false;
bool spaceAppear = false;
while(*s != '\0')
{
if (*s == '.')
{
if (dotAppear || eAppear || spaceAppear)
return false;
else
dotAppear = true;
}
else if (*s == 'e' || *s == 'E')
{
if (eAppear || !firstPart || spaceAppear)
return false;
else
eAppear = true;
}
else if (isdigit(*s))
{
if (spaceAppear)
return false;
if (!eAppear)
firstPart = true;
else
secondPart = true;
}
else if (*s == '+' || *s == '-')
{
if (spaceAppear)
return false;
if (!eAppear || !(*(s-1) == 'e' || *(s-1) == 'E'))
return false;
}
else if (isspace(*s))
spaceAppear = true;
else
return false;
s++;
}
if (!firstPart)
return false;
else if (eAppear && !secondPart)
return false;
else
return true;
}
};
view raw valid number hosted with ❤ by GitHub

No comments:

Post a Comment

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...