zoukankan      html  css  js  c++  java
  • LeetCode OJ-- Valid Number **@

    https://oj.leetcode.com/problems/valid-number/

    判断给的串,是不是合理的 数字形式

    主要问题在需求定义上吧

    class Solution {
    public:
        bool isNumber(const char *s) {
            if(s == NULL)
                return false;
            
            int index = 0;
            // remove heading spaces
            while(s[index] != '' && s[index] == ' ')
                index++;
            
            // only has spaces
            if(s[index] == '')
                return false;
            
            // check + or - allowed
            if(s[index] == '+' || s[index] == '-')
                index++;
                
            // remove tailing spaces
            bool hasSpace = false;
            int tailIndex = 0;
            for(int i = index; s[i] != ''; i++)
            {
                if(s[i] == ' ')
                {
                    if(hasSpace == false)
                        tailIndex = i - 1;
                    hasSpace = true;
                    continue;
                }
                else if(hasSpace && s[i] != ' ')
                    return false;
            
                if(hasSpace == false)
                    tailIndex = i;
            }
            
            
            // check only one . and e or digits allowed 
         // . e can't both exists. and 8. is valid
         // before e and after e must has digits
         // + - before them must be e
    bool hasNum = false; bool hasDot = false; bool hasE = false; for(int i = index; i != tailIndex + 1 && s[i] != ''; i++) { if(s[i] >= '0' && s[i] <= '9') hasNum = true; else if(s[i] == '.') { if(hasDot || hasE) return false; hasDot = true; } else if(s[i] == 'e') { if(hasE || hasNum == false) return false; hasE = true; hasNum = false; } else if(s[i] == '+' || s[i] == '-') { if(!(i > 1 && s[i-1] == 'e')) return false; hasNum = false; } else return false; } return hasNum; } };
  • 相关阅读:
    HDU 1501 Zipper(DFS)
    HDU 2181 哈密顿绕行世界问题(DFS)
    HDU 1254 推箱子(BFS)
    HDU 1045 Fire Net (DFS)
    HDU 2212 DFS
    HDU 1241Oil Deposits (DFS)
    HDU 1312 Red and Black (DFS)
    HDU 1010 Tempter of the Bone(DFS+奇偶剪枝)
    HDU 1022 Train Problem I(栈)
    HDU 1008 u Calculate e
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3918231.html
Copyright © 2011-2022 走看看