Skip to content

Commit a37e9c8

Browse files
committed
add leetcode: offer-20-67
1 parent e7f7d81 commit a37e9c8

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package offer;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
/**
7+
* @author : CodeWater
8+
* @create :2022-07-18-23:26
9+
* @Function Description :20. 表示数值的字符串
10+
*/
11+
public class _20StringThatIndicatesNumbericalValues {
12+
class Solution {
13+
public boolean isNumber(String s) {
14+
Map[] states = {
15+
new HashMap<Object, Object>() {{ put(' ', 0); put('s', 1); put('d', 2); put('.', 4); }}, // 0.
16+
new HashMap<Object, Object>() {{ put('d', 2); put('.', 4); }}, // 1.
17+
new HashMap<Object, Object>() {{ put('d', 2); put('.', 3); put('e', 5); put(' ', 8); }}, // 2.
18+
new HashMap<Object, Object>() {{ put('d', 3); put('e', 5); put(' ', 8); }}, // 3.
19+
new HashMap<Object, Object>() {{ put('d', 3); }}, // 4.
20+
new HashMap<Object, Object>() {{ put('s', 6); put('d', 7); }}, // 5.
21+
new HashMap<Object, Object>() {{ put('d', 7); }}, // 6.
22+
new HashMap<Object, Object>() {{ put('d', 7); put(' ', 8); }}, // 7.
23+
new HashMap<Object, Object>() {{ put(' ', 8); }} // 8.
24+
};
25+
int p = 0;
26+
char t;
27+
for(char c : s.toCharArray()) {
28+
if(c >= '0' && c <= '9') t = 'd';
29+
else if(c == '+' || c == '-') t = 's';
30+
else if(c == 'e' || c == 'E') t = 'e';
31+
else if(c == '.' || c == ' ') t = c;
32+
else t = '?';
33+
if(!states[p].containsKey(t)) return false;
34+
p = (int)states[p].get(t);
35+
}
36+
return p == 2 || p == 3 || p == 7 || p == 8;
37+
38+
}
39+
}
40+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package offer;
2+
3+
/**
4+
* @author : CodeWater
5+
* @create :2022-07-18-23:53
6+
* @Function Description :67.把字符串转换成整数
7+
*/
8+
public class _67ConvertStringsToInteger {
9+
class Solution {
10+
public int strToInt(String str) {
11+
char[] c = str.trim().toCharArray();
12+
if( c.length == 0 ) return 0;
13+
// 最大边界bndry = 2147483647 // 10 = 214748364(先除以10方便遍历)
14+
int res = 0 , boundary = Integer.MAX_VALUE / 10;
15+
// 遍历直接从1开始,因为要判断第一个是不是符号位
16+
int i = 1 , sign = 1;
17+
if( c[0] == '-' ) sign = -1;
18+
// 过符号判断,到这里又不等于+,说明一开始不是符号位开头,从0开始
19+
else if( c[0] != '+' ) i = 0;
20+
for( int j = i ; j < c.length ; j++ ){
21+
if(c[j] < '0' || c[j] > '9' ) break;
22+
/*
23+
两种情况越界:
24+
res>bndry 情况一:执行拼接10 * res ≥ 2147483650越界
25+
res=bndry,x>7 情况二:拼接后是 2147483648 或 2147483649 越界(多一位)
26+
(x是遍历下一位的数字,拼接上去之后大于MAX_VALUE)
27+
*/
28+
if( res > boundary || res == boundary && c[j] > '7' )
29+
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
30+
res = res * 10 + ( c[j] - '0' );
31+
}
32+
33+
return sign * res;
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)