|
| 1 | +/** |
| 2 | + * 1805 |
| 3 | + * Number of Different Integers in a String |
| 4 | + ** |
| 5 | + * You are given a string word |
| 6 | + * that consists of digits and lowercase English letters. |
| 7 | + * You will replace every non-digit character with a space. |
| 8 | + * For example, "a123bc34d8ef34" will become " 123 34 8 34". |
| 9 | + * Notice that you are left with some integers |
| 10 | + * that are separated by at least one space: "123", "34", "8", and "34". |
| 11 | + * |
| 12 | + * Return the number of different integers |
| 13 | + * after performing the replacement operations on word. |
| 14 | + * Two integers are considered different |
| 15 | + * if their decimal representations without any leading zeros are different. |
| 16 | + * |
| 17 | + * Example 1: |
| 18 | + * Input: word = "a123bc34d8ef34" |
| 19 | + * Output: 3 |
| 20 | + * Explanation: |
| 21 | + * The three different integers are "123", "34", and "8". |
| 22 | + * Notice that "34" is only counted once. |
| 23 | + * |
| 24 | + * Example 2: |
| 25 | + * Input: word = "leet1234code234" |
| 26 | + * Output: 2 |
| 27 | + * |
| 28 | + * Example 3: |
| 29 | + * Input: word = "a1b01c001" |
| 30 | + * Output: 1 |
| 31 | + * Explanation: |
| 32 | + * The three integers "1", "01", and "001" all represent the same integer because |
| 33 | + * the leading zeros are ignored when comparing their decimal values. |
| 34 | + * |
| 35 | + * Constraints: |
| 36 | + * • 1 <= word.length <= 1000 |
| 37 | + * • word consists of digits and lowercase English letters. |
| 38 | + * |
| 39 | + * Hint 1: |
| 40 | + * Try to split the string so that each integer is in a different string. |
| 41 | + * |
| 42 | + * Hint 2: |
| 43 | + * Try to remove each integer's leading zeroes |
| 44 | + * and compare the strings to find how many of them are unique. |
| 45 | + ** |
| 46 | + * https://leetcode.com/problems/number-of-different-integers-in-a-string/ |
| 47 | +***/ |
| 48 | + |
| 49 | +using System.Collections.Generic; |
| 50 | + |
| 51 | +namespace Problems; |
| 52 | + |
| 53 | +public class NumberOfDifferentIntegersInAString |
| 54 | +{ |
| 55 | + public int NumDifferentIntegers( string word ) |
| 56 | + { |
| 57 | + HashSet<string> nums = []; |
| 58 | + |
| 59 | + for ( int i = 0; i < word.Length; i++ ) |
| 60 | + { |
| 61 | + if ( char.IsDigit( word[i] ) ) |
| 62 | + { |
| 63 | + int j = i + 1; |
| 64 | + |
| 65 | + while ( j < word.Length && char.IsDigit( word[j] ) ) |
| 66 | + { |
| 67 | + j++; |
| 68 | + } |
| 69 | + |
| 70 | + while ( i < j - 1 && word[i] == '0' ) |
| 71 | + { |
| 72 | + i++; |
| 73 | + } |
| 74 | + |
| 75 | + nums.Add( word[i..j] ); |
| 76 | + |
| 77 | + i = j; |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + return nums.Count; |
| 82 | + } |
| 83 | +} |
0 commit comments