leetcode初级算法6.字符串转整数(atoi)
生活随笔
收集整理的這篇文章主要介紹了
leetcode初级算法6.字符串转整数(atoi)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
leetcode初級(jí)算法6.字符串轉(zhuǎn)整數(shù)(atoi)
僅為個(gè)人刷題記錄,不提供解題思路
題解與收獲
我的解法:
public int myAtoi(String s) {//避免魔法值先設(shè)spaceString space = " ";//如果是空或者是一串空字符串就滾回去!if(s == null || s.replace(space,"").equals("")){return 0;}//拆分s字符串char[] chars = s.toCharArray();int length = chars.length;//記錄空格的數(shù)量int count = 0;//最后整數(shù)的符號(hào),默認(rèn)為正String symbol = "+";//用來(lái)拼接符號(hào)和數(shù)字的變量,一會(huì)要轉(zhuǎn)成long類(lèi)型String result = "";//通過(guò)下面的循環(huán)定位到前置若干個(gè)空格的下一個(gè)字符for(int i = 0; i < length; i++){if(chars[i] == ' '){count++;}else{break;}}//如果是負(fù)號(hào)if(chars[count] == '-'){result += "-";symbol = "-";count++;}else if(chars[count] == '+'){//如果是正號(hào)count++;}else if(Character.isDigit(chars[count])){//如果是數(shù)字,就默認(rèn)返回的數(shù)字為正result += chars[count++];}else{//既不是數(shù)字也不是+,-,說(shuō)明是其他字符,直接返回0return 0;}//遍歷后面的字符,是數(shù)字就加上,不是就直接break掉for(int i = count; i < length; i++){if(Character.isDigit(chars[i])){result += chars[i];}else{break;}}//可能出現(xiàn)下面兩種情況,出現(xiàn)了就立馬return 0;if(result.equals("-") || "".equals(result)){return 0;}//這里惡心我好久,如果甚至連long都不能存這個(gè)數(shù)字(不夠長(zhǎng)),則直接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) {//進(jìn)到這里說(shuō)明確實(shí)存不了這么長(zhǎng)的,直接根據(jù)符號(hào)return對(duì)的數(shù)字回去return symbol.equals("+") ? Integer.MAX_VALUE : Integer.MIN_VALUE;}//如果try catch塊沒(méi)有異常,說(shuō)明順利轉(zhuǎn)成了long,并且經(jīng)過(guò)了三目運(yùn)算符得到正確值了,可以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;} }說(shuō)實(shí)話(huà),看都看不太明白,但是這道題的核心應(yīng)該是確定一個(gè)邊界以及正負(fù)問(wèn)題,有機(jī)會(huì)就去研究一下評(píng)論區(qū)大神的解法。
時(shí)間復(fù)雜度忒高了23333
總結(jié)
以上是生活随笔為你收集整理的leetcode初级算法6.字符串转整数(atoi)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 安卓手机与电脑无线同屏(安卓手机与电脑无
- 下一篇: 千兆网设置(怎样设置千兆网络)