Leetcode 65. Valid Number

Problem

Validate if a given string can be interpreted as a decimal number.

Algorithm

Divided the number into some fragment:

  • before ‘.’, before ‘.’ there can be nothing;
  • before ‘e’, if there is a ‘.’ it must be in front of the ‘e’;
  • the last part.

There are also some type that do not satisfy the form:

  • e.*’, ‘e’ before ‘.’;
  • ‘*e’, nothing after ‘e’;
  • ‘e*’, nothing before ‘e’;
  • ‘’, nothing.

Code

class Solution:
    def isNumber(self, s: str) -> bool:
        slen = len(s)
        
        start = 0
        while start < slen and s[start]:
            if s[start] == ' ':
                start += 1
            else:
                break
        if start < slen and (s[start] == '+' or s[start] == '-'): # +/-****
            start += 1
        
        end = slen-1
        while end >= start and s[end]:
            if s[end] == ' ':
                end -= 1
            else:
                break
        
        e_index = -1
        dot_index = -1
        for i in range(start, end+1):
            if s[i] == 'e':
                e_index = i
            if s[i] == '.' and dot_index == -1:
                dot_index = i
        
        if e_index > -1 and dot_index > e_index: # **e**.**
            return False
        
        flag1 = 0
        if dot_index > -1: # **.
            for i in range(start, dot_index):
                if s[i] < '0' or s[i] > '9':
                    return False
                flag1 = 1
            start = dot_index + 1
        
        flag2 = 0
        if e_index > -1: # ''**e'
            for i in range(start, e_index):
                if s[i] < '0' or s[i] > '9':
                    return False
                flag2 = 1
            e_index += 1
            if e_index < end and (s[e_index] == '+' or s[e_index] == '-'):
                e_index += 1
            start = e_index
        
        if not flag1 and e_index > -1 and not flag2: # 'e**''
            return False
        
        if (not flag1 and not flag2 or e_index > -1) and start > end: # '' / '**e'
            return False
        
        for i in range(start, end+1):
            if s[i] < '0' or s[i] > '9':
                return False 
        
        return True

你可能感兴趣的:(解题报告)