leetcode初级算法6.字符串转整数(atoi)
仅为个人刷题记录,不提供解题思路
题解与收获
我的解法:
public int myAtoi(String s) {//避免魔法值先设spaceString space = " ";//如果是空或者是一串空字符串就滚回去!if(s == null || s.replace(space,"").equals("")){return 0;}//拆分s字符串char[] chars = s.toCharArray();int length = chars.length;//记录空格的数量int count = 0;//最后整数的符号,默认为正String symbol = "+";//用来拼接符号和数字的变量,一会要转成long类型String result = "";//通过下面的循环定位到前置若干个空格的下一个字符for(int i = 0; i < length; i++){if(chars[i] == ' '){count++;}else{break;}}//如果是负号if(chars[count] == '-'){result += "-";symbol = "-";count++;}else if(chars[count] == '+'){//如果是正号count++;}else if(Character.isDigit(chars[count])){//如果是数字,就默认返回的数字为正result += chars[count++];}else{//既不是数字也不是+,-,说明是其他字符,直接返回0return 0;}//遍历后面的字符,是数字就加上,不是就直接break掉for(int i = count; i < length; i++){if(Character.isDigit(chars[i])){result += chars[i];}else{break;}}//可能出现下面两种情况,出现了就立马return 0;if(result.equals("-") || "".equals(result)){return 0;}//这里恶心我好久,如果甚至连long都不能存这个数字(不够长),则直接try catchlong l = 0;try {l = Long.parseLong(result);l = symbol.equals("+") ? Math.min(l, (long) Integer.MAX_VALUE) : Math.max(l, (long) Integer.MIN_VALUE);} catch (Exception e) {//进到这里说明确实存不了这么长的,直接根据符号return对的数字回去return symbol.equals("+") ? Integer.MAX_VALUE : Integer.MIN_VALUE;}//如果try catch块没有异常,说明顺利转成了long,并且经过了三目运算符得到正确值了,可以returnreturn (int)l;}
官方题解
class Solution {public int myAtoi(String str) {Automaton automaton = new Automaton();int length = str.length();for (int i = 0; i < length; ++i) {automaton.get(str.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"});}};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;}}private int get_col(char c) {if (c == ' ') {return 0;}if (c == '+' || c == '-') {return 1;}if (Character.isDigit(c)) {return 2;}return 3;}
}
说实话,看都看不太明白,但是这道题的核心应该是确定一个边界以及正负问题,有机会就去研究一下评论区大神的解法。
时间复杂度忒高了23333