forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStrong Password Checker.java
80 lines (71 loc) · 2.53 KB
/
Strong Password Checker.java
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class Solution {
private static final int MIN_LENGTH = 6;
private static final int MAX_LENGTH = 20;
public int strongPasswordChecker(String password) {
int numMissingComponents = getNumberOfMissingComponents(password);
int n = password.length();
if (n < MIN_LENGTH) {
return Math.max(numMissingComponents, MIN_LENGTH - n);
}
List<Integer> repeats = buildRepeatList(password);
int over = Math.max(0, n - MAX_LENGTH);
int numRemoval = over;
// use overage for repeat % 3 == 0 case. One removal would reduce one replacement
for (int i = 0; i < repeats.size() && over > 0; i++) {
int repeat = repeats.get(i);
if (repeat >= 3 && repeat % 3 == 0) {
repeats.set(i, repeat - 1);
over--;
}
}
// use overage for repeat % 3 == 1 case. Two removal would reduce one replacement
for (int i = 0; i < repeats.size() && over > 0; i++) {
int repeat = repeats.get(i);
if (repeat >= 3 && repeat % 3 == 1) {
repeats.set(i, repeat - Math.min(over, 2));
over -= Math.min(over, 2);
}
}
int numReplace = 0;
for (int repeat : repeats) {
if (over > 0 && repeat >= 3) {
int reduce = Math.min(over, repeat - 2);
over -= reduce;
repeat -= reduce;
}
if (repeat >= 3) {
numReplace += repeat / 3;
}
}
return Math.max(numReplace, numMissingComponents) + numRemoval;
}
private List<Integer> buildRepeatList(String password) {
List<Integer> repeats = new ArrayList<>();
for (int i = 0; i < password.length(); i++) {
if (i == 0 || password.charAt(i) != password.charAt(i - 1)) {
repeats.add(1);
} else {
int last = repeats.size() - 1;
repeats.set(last, repeats.get(last) + 1);
}
}
return repeats;
}
private int getNumberOfMissingComponents(String password) {
int digit = 1;
int upper = 1;
int lower = 1;
for (char c: password.toCharArray()) {
if (Character.isDigit(c)) {
digit = 0;
}
if (Character.isLowerCase(c)) {
lower = 0;
}
if (Character.isUpperCase(c)) {
upper = 0;
}
}
return digit + upper + lower;
}
}