-
Notifications
You must be signed in to change notification settings - Fork 4
/
BiggestTwoDigitValueStringFragment.java
69 lines (57 loc) · 2.01 KB
/
BiggestTwoDigitValueStringFragment.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
package algorithms.assessments;
import org.junit.Test;
import java.util.Comparator;
import java.util.PriorityQueue;
import static org.junit.Assert.assertEquals;
/**
* https://gist.github.com/cenkc/9a9155da530de5c1c898446f29e5d643
*
* created by Cenk Canarslan on 2021-07-12
*/
public class BiggestTwoDigitValueStringFragment {
@Test
public void testBiggestTwoDigit() {
assertEquals(55, solution("50552"));
assertEquals(10, solution("10101"));
assertEquals(88, solution("88"));
assertEquals(-1, solution("1"));
assertEquals(-1, solution("01"));
assertEquals(-1, solution("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789011")); //len 102
}
public int solution(String S) {
if (S.length() < 2 || S.length() > 100
|| S.charAt(0) == '0') {
return -1;
}
int result = Integer.MIN_VALUE;
for (int i = 0; i < S.length() - 1; i++) {
if ( ! Character.isDigit(S.charAt(i)) || ! Character.isDigit(S.charAt(i + 1))) {
return -1;
}
result = Math.max(Integer.parseInt(S.substring(i, i + 2)), result);
}
return result;
}
/**
* Naive solution with PriorityQueue (max)
* @param S
* @return
*/
public int solution2(String S) {
if (S.length() < 2 || S.length() > 100 || S.charAt(0) == '0') return -1;
// Comparator<Integer> comp = Collections.reverseOrder();
// PriorityQueue<Integer> pq = new PriorityQueue<>(comp);
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (o2 > o1) return 1;
if (o1 > o2) return -1;
return 0;
}
});
for (int i = 0; i < S.length() - 1; i++) {
pq.add(Integer.valueOf(S.substring(i, i+2)));
}
return pq.peek();
}
}