1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| class Solution{ class Automaton { int sign = 1; long ans = 0; final String START ="start"; final String SIGN ="signd"; final String IN_NUMBER="in_number"; final String END ="end"; String state = START; private Map<String, String[]> map = new HashMap<>(){{ put("start",new String[]{START,SIGN,IN_NUMBER,END}); put("signd",new String[]{END,END,IN_NUMBER,END}); put("in_number",new String[]{END,END,IN_NUMBER,END}); put("end",new String[]{END,END,END,END}); }} private int getState(char c){ if(c==' '){ return 0; } if(c == '-'||c=='+'){ return 1; } if(c >= '0' && c <= '9'){ return 2; } return 3; } public void get(char c) { state = map.get(state)[getState(c)]; if(IN_NUMBER.equals(state)){ ans = ans * 10 + c - '0'; if(sign == 1){ ans =Math.min(ans,Integer.MAX_VALUE); }else{ ans = Math.min(ans, -(long)Integer.MIN_VALUE); } }else if(SIGN.equals(state)){ sign = c =='+'?1:-1; } }
} public int myAtoi(String str) { Automaton an = new Automaton(); char[] charry =str.toCharArray(); for(char c : charry){ an.get(c); } return an.sign * ((int)an.ans); }
}
|