← Back to index
HardPHP3 min read

Valid Number

validate if string represents a valid number using state machine or regex.

stringstate-machine

Problem link

View on LeetCode

Solutions in this repo

  • PHP../valid-number/solution.phpPHP solution

use finite state machine to track parsing state. valid number can have optional sign, digits, optional decimal point, optional exponent with sign and digits.

states track: seen sign, seen digits, seen decimal, seen exponent, etc. transition between states based on current character. final state must be valid number state.

valid formats

  • integers: "123", "+123", "-123"
  • decimals: "123.45", ".45", "123."
  • scientific: "123e10", "123e-10", "123.45e10"

complexity

O(n) time to process string once. O(1) space for state tracking. efficient state machine approach.