zoukankan      html  css  js  c++  java
  • [leetcode]Valid Number

    看着非常简单,leetcode上面通过率极低...

    可以用正则表达式,不过面试肯定不是让你写个就ok了。。

    所以我们自己来构造DFA吧。。。

    写个表TAT

    在各种数据的调试下,更改状态才过了(详情见照片上的修改

    enum Op{
        Operator, //0
        Digit, // 1
        E, // 2
        Dot, //3
        Space,// 4
        Invalid
    };
    int table[][5] = {
        {1,2,-1,8,-1},
        {-1,2,-1,8,-1},
        {-1,2,4,3,-1},
        {-1,7,4,-1,-1},
        {5,6,-1,-1,-1},
        {-1,6,-1,-1,-1},
        {-1,6,-1,-1,-1},
        {-1,7,4,-1,-1},
        {-1,9,-1,-1,-1},
        {-1,9,4,-1,-1}
    
    };
    class Solution {
    public:
        bool trim(string& s) {
            int start = 0;
            int end = s.size() - 1;
            while(start <= end && s[start] == ' ') start++;
            while(end >= 0 && s[end] == ' ') end--;
            if(end >= start) s = s.substr(start , end - start + 1);
            else return false;
            return true;
        }
        Op getOp(char ch) {
            if(ch == '+' || ch == '-') return Operator;
            if(ch >= '0' && ch <= '9') return Digit;
            if(ch == 'e') return E;
            if(ch == '.') return Dot;
            if(ch == ' ') return Space;
            return Invalid;
        }
        bool isNumber(const char *s) {
            string str = s;
            if(!trim(str)) return false;
            int pos = 0;
            int size = str.size();
            int state = 0;
            while(pos < size) {
                char ch = str[pos];
                Op x = getOp(ch);
                if(x == Invalid) return false;
                state = table[state][(int)x];
                if(state == -1) return false;
                pos++;
            }
            return state == 2 || state == 6  || state == 7 || state == 3 || state == 9;
        }
    };
  • 相关阅读:
    数据结构(2)-链表
    数据结构(1)-数组
    SpringMVC学习总结(一)--Hello World入门
    基本数据类型对象的包装类
    关于String的相关常见方法
    常见的集合容器应当避免的坑
    再一次生产 CPU 高负载排查实践
    分表后需要注意的二三事
    线程池没你想的那么简单(续)
    线程池没你想的那么简单
  • 原文地址:https://www.cnblogs.com/x1957/p/3517617.html
Copyright © 2011-2022 走看看