字符串转换整数(LeetCode No.8)
第一次解用了两个循环,第一个构造有效的字符串,第二个转换为数字。官方题解用的自动机,是优秀思路。
class Solution {
public int myAtoi(String s) {
//start:0,signed:1,number:2,end:3
//状态矩阵
//[start][signed][number][end]
//[end] [end] [number][end]
//[end] [end] [number][end]
//[end] [end] [end] [end]
Automachine automachine = new Automachine();
for(int i=0;i<s.length();i++){
automachine.check(s.charAt(i));
}
return (int)(automachine.signed * automachine.res);
}
}
class Automachine{
private int state = 0;
public int signed = 1;
public long res = 0;
private int[][] state_table = {{0,1,2,3},{3,3,2,3},{3,3,2,3},{3,3,3,3}};
public void check(char c){
state = state_table[state][get_state(c)];
if(state == 2){
//进入数字状态,判断数字,并根据符号判断是否溢出
res = res * 10 + c - '0';
res = signed == 1?Math.min(res,(long)Integer.MAX_VALUE):Math.min(res,-(long)Integer.MIN_VALUE);
}else if(state == 1){
//进入符号状态,判断符号
signed = c == '+'?1:-1;
}else if(state == 3){
return;
}
}
private int get_state(char c){
if(c==' ')return 0;
if(c=='+'||c=='-')return 1;
if(Character.isDigit(c))return 2;
return 3;
}
}