Leetcode 1805. Number of Different Integers in a String
You are given a string word
consisting of digits and lowercase English letters. You need to extract all the different integers that are present in the string and return the count of these distinct integers.
An integer is a contiguous sequence of digits within the string. Leading zeros are allowed in an integer but they should be ignored while determining if two integers are distinct.
word
will be between 1 and 1000.import java.util.HashSet;
import java.util.Set;
public class Solution {
public int numDifferentIntegers(String word) {
Set<String> uniqueIntegers = new HashSet<>();
int n = word.length();
int i = 0;
while (i < n) {
// Skip non-digit characters
while (i < n && !Character.isDigit(word.charAt(i))) {
i++;
}
if (i < n && Character.isDigit(word.charAt(i))) {
int j = i;
// Find the end of the digit sequence
while (j < n && Character.isDigit(word.charAt(j))) {
j++;
}
// Extract the number sequence
String number = word.substring(i, j);
// Remove leading zeros
number = number.replaceFirst("^0+(?!$)", "");
// Add the normalized number to the set
uniqueIntegers.add(number);
// Move to the next segment
i = j;
}
}
return uniqueIntegers.size();
}
public static void main(String[] args) {
Solution solution = new Solution();
String input = "a123bc34d8ef34";
System.out.println(solution.numDifferentIntegers(input)); // Output: 3
}
}
Thus, the overall time complexity is O(n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?