# 第六周ARTS总结

# Algorithm

3ms | 62.44% Run time
35.3MB | 99.97% Memory

public int myAtoi(String str) {
    // empty
    if (str == null || str.length() == 0 || str.trim().length() == 0) {
        return 0;
    }

    StringBuilder stringBuilder = new StringBuilder();
    for (char ch : str.trim().toCharArray()) {
        if (stringBuilder.length() == 0 && (ch == '+' || ch == '-')) {
            stringBuilder.append(ch);
            continue;
        }

        if (Character.isDigit(ch)) {
            stringBuilder.append(ch);
        } else {
            break;
        }
    }

    // if empty
    if (stringBuilder.length() == 0) {
        return 0;
    }

    // if -
    if ("-".equals(stringBuilder.toString()) || "+".equals(stringBuilder.toString())) {
        return 0;
    }

    try {
        return Integer.parseInt(stringBuilder.toString());
    } catch (NumberFormatException ex) {
        if (stringBuilder.toString().startsWith("-")) {
            return Integer.MIN_VALUE;
        } else {
            return Integer.MAX_VALUE;
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

# Review

# Tip

  • 断言:指明某个字符串前边或者后边将会出现满足某种规律的字符串。
    想指定xxx前肯定会出现<title>,就用反向肯定预查,表达式:(?<=<title>)·*
    想指定xxx后肯定会出现</title>,就用正向肯定预查,表达式:.*(?=</title>)
    因此<title>xxx</title>通过(?<=<title>).*(?=</title>)就能匹配到xxx。

# Share

暂无内容

更新时间: 10/20/2022, 7:04:01 AM