LeetCode 66 Valid Number

来源:互联网 发布:淘宝号安全风险 编辑:程序博客网 时间:2024/06/05 03:10

Validate if a given string is numeric.

Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.

思路1:使用有限状态机,空间复杂度为O(n),时间复杂度为O(n),本思路来自龚陆安(http://weibo.com/luangong),只不过原作者使用的是c++,我将其改写为java。

public class Solution {public boolean isNumber(String s) {int transitionTable[][] = new int[][] {{ -1, 0, 3, 1, 2, -1 }, // next states for state 0{ -1, 8, -1, 1, 4, 5 }, // next states for state 1{ -1, -1, -1, 4, -1, -1 }, // next states for state 2{ -1, -1, -1, 1, 2, -1 }, // next states for state 3{ -1, 8, -1, 4, -1, 5 }, // next states for state 4{ -1, -1, 6, 7, -1, -1 }, // next states for state 5{ -1, -1, -1, 7, -1, -1 }, // next states for state 6{ -1, 8, -1, 7, -1, -1 }, // next states for state 7{ -1, 8, -1, -1, -1, -1 } // next states for state 8};int state = 0;for (int i = 0; i < s.length(); ++i) {int inputType = 0;if (Character.isSpaceChar(s.charAt(i)))inputType = 1;else if (s.charAt(i) == '+' || s.charAt(i) == '-')inputType = 2;else if (Character.isDigit(s.charAt(i)))inputType = 3;else if (s.charAt(i) == '.')inputType = 4;else if (s.charAt(i) == 'e' || s.charAt(i) == 'E')inputType = 5;// Get next state from current state and input symbolstate = transitionTable[state][inputType];// Invalid inputif (state == -1)return false;}// If the current state belongs to one of the accepting (final) states,// then the number is validreturn state == 1 || state == 4 || state == 7 || state == 8;}}

思路2 java中可以使用正则表达式,我们可以使用正则表达式来处理。

public class Solution {public boolean isNumber(String s) {    //首先删除字符串首位和尾部的空格    String str=s.replaceAll("(^\\s+)|(\\s+$)", "");if(str.length()==0) return false;boolean [] temp=new boolean[6];boolean result=false;temp[0]=str.matches("(-|\\+)?\\d+(\\.)?");temp[1]=str.matches("(-|\\+)?\\d+\\.\\d+");temp[2]=str.matches("(-|\\+)?\\.\\d+");temp[3]=str.matches("(-|\\+)?\\d+(\\.)?(e|E)(-|\\+)?\\d+");temp[4]=str.matches("(-|\\+)?\\d+\\.\\d+(e|E)(-|\\+)?\\d+");temp[5]=str.matches("(-|\\+)?\\.\\d+(e|E)(-|\\+)?\\d+");for(int i=0;i<6;i++){result=result||temp[i];}return result;}}

思路3:与思路2相同,只不过对正则表达式进行了精简。

public boolean isNumber(String s) { String str=s.trim();//删除两端的空格if(str.length()==0) return false;boolean [] temp=new boolean[4];temp[0]=str.matches("(-|\\+)?\\d+(\\.)?");temp[1]=str.matches("(-|\\+)?(\\d+)?(\\.)?\\d+");temp[2]=str.matches("(-|\\+)?\\d+(\\.)?(e|E)(-|\\+)?\\d+");temp[3]=str.matches("(-|\\+)?(\\d+)?(\\.)?\\d+(e|E)(-|\\+)?\\d+");return temp[0]||temp[1]||temp[2]||temp[3];}



1 0