当前位置:网站首页>LeetCode 8. String conversion integer (ATOI)
LeetCode 8. String conversion integer (ATOI)
2022-07-06 00:09:00 【Daylight629】
8. String conversion integers (atoi)
Please come to realize a myAtoi(string s) function , Enable it to convert a string to a 32 Bit signed integer ( similar C/C++ Medium atoi function ).
function myAtoi(string s) The algorithm is as follows :
- Read in strings and discard useless leading spaces
- Check the next character ( Suppose you haven't reached the end of the character yet ) Positive or negative , Read the character ( If there is ). Determine whether the final result is negative or positive . If neither exists , Suppose the result is positive .
- Read in the next character , Until you reach the next non numeric character or the end of the input . The rest of the string will be ignored .
- Convert the numbers read in the previous steps into integers ( namely ,“123” -> 123, “0032” -> 32). If you don't read in the numbers , Then the integer is
0. Change the symbol if necessary ( From step 2 Start ). - If the number of integers exceeds 32 Bit signed integer range
[−231, 231 − 1], You need to truncate this integer , Keep it in this range . say concretely , Less than−231The integer of should be fixed to−231, Greater than231 − 1The integer of should be fixed to231 − 1. - Returns an integer as the final result .
Be careful :
- The white space character in this question only includes the space character
' '. - Except for the leading space or the rest of the string after the number , Do not ignore Any other character .
Example 1:
Input :s = "42"
Output :42
explain : The bold string is the character that has been read in , The caret is the character currently read .
The first 1 Step :"42"( No characters are currently read in , Because there are no leading spaces )
^
The first 2 Step :"42"( No characters are currently read in , Because it doesn't exist here '-' perhaps '+')
^
The first 3 Step :"42"( Read in "42")
^
Parse to get an integer 42 .
because "42" In scope [-231, 231 - 1] Inside , The final result is 42 .
Example 2:
Input :s = " -42"
Output :-42
explain :
The first 1 Step :" -42"( Read in leading space , But ignore )
^
The first 2 Step :" -42"( Read in '-' character , So the result should be negative )
^
The first 3 Step :" -42"( Read in "42")
^
Parse to get an integer -42 .
because "-42" In scope [-231, 231 - 1] Inside , The final result is -42 .
Example 3:
Input :s = "4193 with words"
Output :4193
explain :
The first 1 Step :"4193 with words"( No characters are currently read in , Because there are no leading spaces )
^
The first 2 Step :"4193 with words"( No characters are currently read in , Because it doesn't exist here '-' perhaps '+')
^
The first 3 Step :"4193 with words"( Read in "4193"; Because the next character is not a number , So read in stop )
^
Parse to get an integer 4193 .
because "4193" In scope [-231, 231 - 1] Inside , The final result is 4193 .
Example 4:
Input :s = "words and 987"
Output :0
explain :
The first 1 Step :"words and 987"( No characters are currently read in , Because there are no leading spaces )
^
The first 2 Step :"words and 987"( No characters are currently read in , Because it doesn't exist here '-' perhaps '+')
^
The first 3 Step :"words and 987"( Because of the current character 'w' It's not a number , So read in stop )
^
Parse to get an integer 0 , Because I didn't read in any numbers .
because 0 In scope [-231, 231 - 1] Inside , The final result is 0 .
Example 5:
Input :s = "-91283472332"
Output :-2147483648
explain :
The first 1 Step :"-91283472332"( No characters are currently read in , Because there are no leading spaces )
^
The first 2 Step :"-91283472332"( Read in '-' character , So the result should be negative )
^
The first 3 Step :"-91283472332"( Read in "91283472332")
^
Parse to get an integer -91283472332 .
because -91283472332 Less than range [-231, 231 - 1] Lower bound of , The final result is truncated to -231 = -2147483648 .
Tips :
0 <= s.length <= 200sBy the English letters ( Uppercase and lowercase )、 Numbers (0-9)、' '、'+'、'-'and'.'form
Two 、 Method 1
automata
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;
}
}
Complexity analysis
Time complexity :O(n), among n Is the length of the string . We just need to process all the characters in turn , The time required to process each character is O(1).
Spatial complexity :O(1). The state of automata only needs constant space to store .
边栏推荐
- FFMPEG关键结构体——AVFormatContext
- My colleagues quietly told me that flying Book notification can still play like this
- Effet Doppler (déplacement de fréquence Doppler)
- Zhuan: in the future, such an organization can withstand the risks
- openssl-1.0.2k版本升级openssl-1.1.1p
- DEJA_ Vu3d - cesium feature set 055 - summary description of map service addresses of domestic and foreign manufacturers
- Gd32f4xx UIP protocol stack migration record
- About the slmgr command
- [Luogu cf487e] tours (square tree) (tree chain dissection) (line segment tree)
- CloudCompare&PCL 点云随机添加噪声
猜你喜欢

Upgrade openssl-1.1.1p for openssl-1.0.2k
![Choose to pay tribute to the spirit behind continuous struggle -- Dialogue will values [Issue 4]](/img/d8/a367c26b51d9dbaf53bf4fe2a13917.png)
Choose to pay tribute to the spirit behind continuous struggle -- Dialogue will values [Issue 4]

云呐|固定资产管理系统主要操作流程有哪些

Zhongjun group launched electronic contracts to accelerate the digital development of real estate enterprises

Wechat applet -- wxml template syntax (with notes)

Open source CRM customer relationship system management system source code, free sharing

权限问题:source .bash_profile permission denied

Mysql - CRUD

Effet Doppler (déplacement de fréquence Doppler)

Yunna | what are the main operating processes of the fixed assets management system
随机推荐
MySql——CRUD
My colleagues quietly told me that flying Book notification can still play like this
[day39 literature extensive reading] a Bayesian perspective on magnetic estimation
Gd32f4xx UIP protocol stack migration record
Key structure of ffmpeg - avframe
PV静态创建和动态创建
剖面测量之提取剖面数据
转:未来,这样的组织才能扛住风险
Shardingsphere source code analysis
用列表初始化你的vector&&initializer_list简介
【DesignMode】适配器模式(adapter pattern)
FFMPEG关键结构体——AVFrame
Problems encountered in the database
Determinant learning notes (I)
USB Interface USB protocol
The use of El cascader and the solution of error reporting
What if the C disk is not enough? Let's see how I can clean up 25g of temp disk space after I haven't redone the system for 4 years?
【luogu P3295】萌萌哒(并查集)(倍增)
Global and Chinese markets for hinged watertight doors 2022-2028: Research Report on technology, participants, trends, market size and share
Tips for using pads router