Question

Formatted question description: https://leetcode.ca/all/65.html

65	Valid Number

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.

Update (2015-02-10):
The signature of the C++ function had been updated.
If you still see your function signature accepts a const char * argument,
please click the reload button  to reset your code definition.

Algorithm

Maintain a two-dimensional dp array, where dp[i][j] represents the minimum path sum to the current position.

Next, look for the state transition formula, because there are only two cases to reach the current position (i, j), either from the top (i-1, j) or from the left (i, j-1), we choose the dp value The smaller path is to compare dp[i-1][j] with dp[i][j-1], and add the smaller value to the current number grid[i][j], which is the current position dp value.

However, some special cases need to be assigned in advance, such as the starting point position, which is directly assigned to grid[0][0], and the first row and column. The position of the first row can only come from the left, and the position of the first column The position can come from above, so these two lines should be initialized in advance, and then update from the position (1, 1) to the lower right corner.

Code

Java

public class Valid_Number {

	public static void main(String[] args) {

		String s = "3";

        boolean yes = s.matches("^\\s*[+-]?(\\d+\\.?\\d*|\\d*\\.\\d+)(e[+-]?\\d+)?\\s*$");

//		boolean yes = s.matches("\\de\\d+");

		System.out.print(yes);

	}

	public class Solution {
	    public boolean isNumber(String s) {

	        // @note: matches()
	        // return s.matchAll();

	        //     s.matches("^\\s*[+-]?(\\d+\\.?\\d*|\\d*\\.\\d+)(e[+-]?\\d+)?\\s*");
	        return s.matches("^\\s*[+-]?(\\d+\\.?\\d*|\\d*\\.\\d+)(e[+-]?\\d+)?\\s*$");


	        /*
	                Input:	"."
	                Output:	true
	                Expected:	false
	        */
	        // make it 2 parts, with "e" and without "e"
	        // return s.matches("^\\s*[+-]?d*\\.?\\d*\\s*$") || s.matches("^\\s*[+-]?\\d+e[+-]?\\d+\\s*$");
	    }
	}

}

All Problems

All Solutions