[Sword Finger 20] A string representing a numeric value

Method 1: Determine and mark in turn: time O(n), space O(1)

Solution: There are 4 kinds of situations for the value, namely: sign, decimal point, exponent, number, and deal with these four states according to the situation

  1. Sign: It can only appear at the beginning of the value, or one position after e
  2. Decimal point: can only appear in front of e, and only once
  3. Index: There must be numbers on both sides of the index, that is, there must be numbers before and after the index, and they can only appear once
  4. Number: can appear in any position
  5. Others: other occurrences in the number will directly return false
class Solution {
    
    
public:
    bool isNumber(string s) 
    {
    
    
        // 题解:依次判断,统计所有出现数值的情况
        // 1.正负号只能出现在开始或者e后的位置
        // 2.小数点只能出现在e之前,且只能有一个
        // 3.e只能出现一次
        int i = 0;
        // 去除数组首部空格
        while (i < s.size() && s[i] == ' ')
            i++;
        int j = s.size() - 1;
        // 去除数组尾部空格
        while (j >= 0 && s[j] == ' ')
            j--;
        if (i < s.size() && s[i] == '-' || s[i] == '+')
            i++;
        bool is_dig = false, is_pot = false, is_e = false;
        while (i <= j)
        {
    
    
        	// 1.出现数字
            if (s[i] >= '0' && s[i] <= '9')	
                is_dig = true;
            // 2.出现小数点
            else if (s[i] == '.')
            {
    
    
                if (is_e || is_pot)
                    return false;
                is_pot = true;
            }
            // 2.出现正负号
            else if (s[i] == '-' || s[i] == '+')
            {
    
    
                if (s[i - 1] != 'e')
                    return false;
            }
            // 3.出现指数符号
            else if (s[i] == 'e' || s[i] == 'E')
            {
    
    
                if (is_e || !is_dig)
                    return false;
                is_dig = false;
                is_e = true;
                s[i] = 'e';
            }
            // 4.其他
            else 
            {
    
    
                return false;
            }
            i++;
        }
        return is_dig;
    }
};

Guess you like

Origin blog.csdn.net/qq_45691748/article/details/113757490