标签:The new tomato mat lan first etc 不用 efficient
class Solution {
public int myAtoi(String s) {
int ans = 0;
int coefficient = 1;
boolean hasFirst = false;
for(char c : s.toCharArray()){
if(c == ‘ ‘ && !hasFirst){
continue;
} else if ((c == ‘+‘ || c == ‘-‘) && !hasFirst){
hasFirst = true;
if(c == ‘-‘){
coefficient = -1;
}
} else if (c >= ‘0‘ && c <= ‘9‘){
hasFirst = true;
if (coefficient == 1 && (ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE / 10 && c > ‘7‘))){
return Integer.MAX_VALUE;
}
if (coefficient == -1 && (ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE / 10 && c > ‘8‘))){
return Integer.MIN_VALUE;
}
ans = ans * 10 + c - ‘0‘;
} else{
return coefficient * ans;
}
}
return coefficient * ans;
}
}
判断每一个字符,记录是否遇到第一个非空字符,遇到后开始记录符号和数字,记录结束后return。注意判断是否超出int范围。
class Solution {
public int myAtoi(String s) {
Automaton automation = new Automaton();
for(char c : s.toCharArray()){
automation.get(c);
}
return (int) (automation.sign * automation.ans);
}
}
class Automaton {
public int sign = 1;
public long ans = 0;
private String state = "start";
private Map<String, String[]> table = new HashMap<>();
public Automaton(){
table.put("start", new String[]{"start", "signed", "in_number", "end"});
table.put("signed", new String[]{"end", "end", "in_number", "end"});
table.put("in_number", new String[]{"end", "end", "in_number", "end"});
table.put("end", new String[]{"end", "end", "end", "end"});
}
public void get(char c){
state = table.get(state)[get_col(c)];
if(state.equals("in_number")){
ans = ans * 10 + c - ‘0‘;
ans = sign == 1 ? Math.min(ans, (long)Integer.MAX_VALUE) : Math.min(ans, -(long)Integer.MIN_VALUE);
} else if(state.equals("signed")){
sign = c == ‘+‘ ? 1 : -1;
}
}
private int get_col(char c){
if(c == ‘ ‘){
return 0;
}
if(c == ‘+‘ || c == ‘-‘){
return 1;
}
if(c >= ‘0‘ && c <= ‘9‘){
return 2;
}
return 3;
}
}
定义四个状态:start,signed,in_number,end。建立状态转移表:
‘ ‘ | +/- | number | other | |
---|---|---|---|---|
start | start | signed | in_number | end |
signed | end | end | in_number | end |
in_number | end | end | in_number | end |
end | end | end | end | end |
通过输入的字符来转移状态,并记录最终的符号和数字,在in_number状态判断数字是否超出范围。
在具体实现上,定义了一个Automation自动机类,用来记录状态和进行状态转移。使用HashMap存储状态转移表,通过输入的字符和当前的状态,转移到对应的状态。
这种方法思路较为清晰,写起来不用很多if语句,不容易出错。
标签:The new tomato mat lan first etc 不用 efficient
原文地址:https://www.cnblogs.com/xiafrog/p/14309389.html