-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathNumberOfDifferentIntegersInString.java
More file actions
27 lines (25 loc) · 1 KB
/
NumberOfDifferentIntegersInString.java
File metadata and controls
27 lines (25 loc) · 1 KB
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
import java.util.HashSet;
import java.util.Set;
public class NumberOfDifferentIntegersInString {
public int numDifferentIntegers(String word) {
final Set<String> uniqueIntegers = integersInString(word);
return uniqueIntegers.size();
}
private Set<String> integersInString(String s) {
final Set<String> integers = new HashSet<>();
boolean inNumber = false;
StringBuilder current = new StringBuilder();
for (int index = 0 ; index < s.length() ; index++) {
if (Character.isDigit(s.charAt(index))) {
if (!inNumber) inNumber = true;
current.append(s.charAt(index) == '0' && current.length() == 0 ? "" : s.charAt(index));
if (index == s.length() - 1) integers.add(current.toString());
} else if (inNumber) {
inNumber = false;
integers.add(current.toString());
current = new StringBuilder();
}
}
return integers;
}
}