-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathSecondLargestDigitinaString.java
80 lines (55 loc) · 1.33 KB
/
SecondLargestDigitinaString.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
/*
Source: https://leetcode.com/problems/second-largest-digit-in-a-string/
2 Approaches
Time: O(n), where n is the size of the given string s
Space: O(n), char array is needed to check for the character if it's a digit
*/
class Solution {
public int secondHighest(String s) {
int max = -1;
int secondMax = -1;
for(char ch : s.toCharArray()) {
if(isDigit(ch)) {
int digit = ch - '0';
if(digit > max) {
secondMax = max;
max = digit;
} else if (digit > secondMax && digit < max) {
secondMax = digit;
}
}
}
return secondMax;
}
private boolean isDigit(char ch) {
return ch >= '0' && ch <= '9';
}
}
/*
2nd approach
Time: O(n), where n is the size of the given string s
Space: O(1), in-place
*/
class Solution {
public int secondHighest(String s) {
int max = -1;
int secondMax = -1;
int len = s.length();
for(int i = 0; i < len; ++i) {
char ch = s.charAt(i);
if(ch >= '0' && ch <= '9') {
int digit = ch - '0';
if(digit > max) {
secondMax = max;
max = digit;
} else if(digit > secondMax && digit < max) {
secondMax = digit;
}
}
}
return secondMax;
}
private boolean isDigit(char ch) {
return ch >= '0' && ch <= '9';
}
}