LeetCode 1805: Number of Different Integers in a String Solution
Master LeetCode problem 1805 (Number of Different Integers in a String), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1805. Number of Different Integers in a String
Problem Explanation
Explanation:
To solve this problem, we will iterate over the input string and replace non-digit characters with spaces. Then, we will split the string based on spaces and add the distinct integers to a set. Finally, we return the size of the set as the number of different integers in the string.
- Time Complexity: O(n) where n is the length of the input string.
- Space Complexity: O(n) for the set to store distinct integers.
Solution Code
import java.util.HashSet;
import java.util.Set;
class Solution {
public int numDifferentIntegers(String word) {
Set<String> set = new HashSet<>();
word = word.replaceAll("[^0-9]", " ");
for (String num : word.split("\\s+")) {
if (!num.equals("")) {
set.add(num.replaceFirst("^0+(?!$)", ""));
}
}
return set.size();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1805 (Number of Different Integers in a String)?
This page provides optimized solutions for LeetCode problem 1805 (Number of Different Integers in a String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1805 (Number of Different Integers in a String)?
The time complexity for LeetCode 1805 (Number of Different Integers in a String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1805 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1805 in Java, C++, or Python.