LeetCode 1805: Number of Different Integers in a String

Hash TableString

LeetCode 1805 Solution 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.

LeetCode 1805 Solutions in Java, C++, Python

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();
    }
}

Interactive Code Editor for LeetCode 1805

Improve Your LeetCode 1805 Solution

Use the editor below to refine the provided solution for LeetCode 1805. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems