Here is the link.
C# First submission in Sept. 2105
It is time for me to review the algorithm since I came cross the post.
I will write down some highlights for my practice.
- Skip leading space characters;
- Consider edge case: empty string is not a number;
- Skip one char if it is '+' or '-';
- More will be added later. There are a few more cases in the solution.
I also like to write down a few thoughts about the algorithm. Why it is hard, and what I learn from study of discussion posts.
public class Solution {
public bool IsNumber(string s) {
int len = s.Length;
int i = 0, e = len - 1;
while (i <= e && isWhitespace(s[i]))
i++;
if (i > len - 1)
return false;
while (e >= i && isWhitespace(s[e]))
e--;
// skip leading +/-
if (s[i] == '+' || s[i] == '-') i++;
bool isNum = false; // is a digit
bool isDot = false; // is a '.'
bool isExp = false; // is a 'e'
while (i <= e)
{
char c = s[i];
if (isDigit(c))
{
isNum = true;
}
else if (c == '.')
{
if (isExp || isDot)
return false;
isDot = true;
}
else if (c == 'e')
{
if (isExp || isNum == false)
return false;
isExp = true;
isNum = false;
}
else if (c == '+' || c == '-')
{
if (s[i - 1] != 'e') return false;
}
else
{
return false;
}
i++;
}
return isNum;
}
public bool isWhitespace(char c)
{
return c == ' ';
}
public bool isDigit(char c)
{
int no = c - '0';
return no >= 0 && no <= 9;
}
}
No comments:
Post a Comment