判断一个字符串是否是数字 正则表达式 自动机

时间:2023-01-07 08:30:03
我的解法
public class Solution {
    public boolean isNumeric(char[] str) {
        if(str.length==0) return false;
        int e=0;
        int point=0;
        for(int i=0;i<str.length;i++){
            if((str[i]=='+'||str[i]=='-')&&str.length>1&&(i==0||i!=0&&(str[i-1]=='e'||str[i-1]=='E'))){
                continue;
            }
            if(str[i]=='.'&&i!=0&&point==0&&e==0){
                point=1;
                continue;
            }
            if((str[i]=='e'||str[i]=='E')&&i!=0&&i!=str.length-1&&e==0){
                e=1;
                continue;
            }
            if(i==0&&str[i]=='0'&&str.length>1&&str[i+1]=='.'){
                continue;
            }
            if(str[i]>='0'&&str[i]<='9'){
                continue;
            }
            return false;
        }
        return true;
    }
}




正则表达式
public class Solution {
     public boolean isNumeric( char [] str) {
         String string = String.valueOf(str);
         return string.matches( "[\\+-]?[0-9]*(\\.[0-9]*)?([eE][\\+-]?[0-9]+)?" );
     }
}

[]可有可无


编译原理中自动机可以实现,识别如下图所示:

判断一个字符串是否是数字 正则表达式 自动机


class Solution {
public :
     bool isNumeric( char * string)
     {
         int i = 0;
         if (string[i]== '+' || string[i]== '-' || IsNum(string[i])){
             while (string[++i]!= '\0' && IsNum(string[i]));
             if (string[i]== '.' ){
                 if (IsNum(string[++i])){
                     while (string[++i]!= '\0' && IsNum(string[i]));
                     if (string[i]== 'e' ||string[i]== 'E' ){
                         i++;
                         if (string[i]== '+' || string[i]== '-' || IsNum(string[i])){
                             while (string[++i]!= '\0' && IsNum(string[i]));
                             if (string[i]== '\0' ) return true ;
                             else return false ;
                         } else return false ;
                     } else if (string[i]== '\0' ) return true ;
                     else return false ;
                 } else if (string[++i]== '\0' ) return true ;
                 else return false ;
             } else if (string[i]== 'e' ||string[i]== 'E' ){
                 i++;
                 if (string[i]== '+' || string[i]== '-' || IsNum(string[i])){
                     while (string[++i]!= '\0' && IsNum(string[i]));
                     if (string[i]== '\0' ) return true ;
                     else return false ;
                 } else return false ;
             } else if (string[i]== '\0' ) return true ;
             else return false ;           
         } else return false ;
     }
     
     bool IsNum( char ch)
     {
         if (ch< '0' ||ch> '9' ) return false ;
         else return true ;
     }
};