Thursday, July 11, 2019

65. Valid Number

I practiced the algorithm more than 3 years ago. And I just wrote a discuss post to share my practice.

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.
  1. Skip leading space characters;
  2. Consider edge case: empty string is not a number;
  3. Skip one char if it is '+' or '-';
  4. 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