Leetcode–Valid Number

The Problem:

Validate if a given string is numeric.

Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true

Notes:

  1. The problem is ambigous and need to clarify a lot of special cases before implementing. Some cases I found in test cases that are not that intuitive are:
    1. 01 ->true
      e9->false
      3. ->true
      .1 -> true
      46.e3-> true
  2. Notice that for ‘e’ and ‘.’ can only appear once. And all special non-digit characters has rules for the character following. When using flag to mark its immediate follower, need to reset all the flags in all the branches.

Java Solution

public class Solution {

    public boolean isNumber(String s) {
        s = s.trim();
        if(s.length()==0) return false;
        boolean foloDot = false;
        boolean hasExpo = false;
        boolean foloE = false;
        boolean hasDot = false;
        boolean hasSign = false;
        boolean foloSign = false;
        boolean hasNum = false;
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if(ch=='e'){
                if(!hasNum ||hasExpo || foloSign ||  i==s.length()-1)
                    return false;
                hasExpo = true;
                foloE = true;
                foloDot = false;
                foloSign = false;
            }
            else if(ch=='.'){
                if((!hasNum&&i==s.length()-1)  || hasDot || hasExpo )
                    return false;
                hasDot = true;
                foloDot = true;
                foloE = false;
                foloSign = false;
            }
            else if(ch=='+' || ch=='-'){
                if((hasSign && !foloE)|| i==s.length()-1 || (hasNum && !foloE) || foloDot)
                    return false;
                hasSign = true;
                foloSign = true;
                foloDot = false;
                foloE = false;
            }
            else if(ch>='0' && ch <='9'){
                foloDot = false;
                foloE = false;
                foloSign = false;
                hasNum = true;
            }
            else
                return false;
        }
        return true;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s