题目链接:https://leetcode-cn.com/problems/string-to-integer-atoi/
题意:将字符串转换为整数
分析:有限状态自动机的题,以前好像没做过,直接看题解吧
class Solution { public int myAtoi(String s) { Automaton automaton = new Automaton(); int len = s.length(); for(int i=0;i<len;i++){ automaton.get(s.charAt(i)); } return (int)(automaton.sign*automaton.ans); } } class Automaton{ public int sign = 1; public long ans = 0; private String state = "start"; private Map<String,String[]> table = new HashMap<String,String[]>(){{ put("start", new String[]{"start", "signed", "in_number", "end"}); put("signed", 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 get_col(char c){ if(c==' ')return 0; if (c == '+' || c == '-') { return 1; } if (Character.isDigit(c)) { return 2; } return 3; } public void get(char c){ state = table.get(state)[get_col(c)]; if("in_number".equals(state)){ ans = ans*10+c-'0'; ans = sign == 1 ? Math.min(ans, (long) Integer.MAX_VALUE) : Math.min(ans, -(long) Integer.MIN_VALUE); }else if("signed".equals(state)){ sign = c == '+' ?1:-1; } } }