# 第十二周ARTS总结

# Algorithm

1ms | 73.74% Run time
37.7MB | 83.49% Memory

public String longestCommonPrefix(String[] strs) {
    if (strs.length == 0) {
        return "";
    }

    if (strs.length == 1) {
        return strs[0];
    }

    int index = -1;
    while (true) {
        boolean isEqual = true;

        // 判断第 index + 1 位是否一致
        for (int i = 0; i < strs.length - 1; i++) {
            if (strs[i].length() < index + 2 || strs[i + 1].length() < index + 2) {
                isEqual = false;
                break;
            }

            if (strs[i].charAt(index + 1) != strs[i + 1].charAt(index + 1)) {
                isEqual = false;
            }
        }

        // 如果一致,那索引加一
        if (isEqual) {
            index++;
        } else {
            break;
        }
    }

    return strs[0].substring(0, index + 1);
}
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

# Review

# Tip

  • 在Android Studio中可以设置预览尺寸,配合着AutoSize一起用很好用

# Share

暂无内容

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