|
| 1 | +// Source : https://leetcode.com/problems/number-of-different-integers-in-a-string/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2021-03-28 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * You are given a string word that consists of digits and lowercase English letters. |
| 8 | + * |
| 9 | + * You will replace every non-digit character with a space. For example, "a123bc34d8ef34" will become |
| 10 | + * " 123 34 8 34". Notice that you are left with some integers that are separated by at least one |
| 11 | + * space: "123", "34", "8", and "34". |
| 12 | + * |
| 13 | + * Return the number of different integers after performing the replacement operations on word. |
| 14 | + * |
| 15 | + * Two integers are considered different if their decimal representations without any leading zeros |
| 16 | + * are different. |
| 17 | + * |
| 18 | + * Example 1: |
| 19 | + * |
| 20 | + * Input: word = "a123bc34d8ef34" |
| 21 | + * Output: 3 |
| 22 | + * Explanation: The three different integers are "123", "34", and "8". Notice that "34" is only |
| 23 | + * counted once. |
| 24 | + * |
| 25 | + * Example 2: |
| 26 | + * |
| 27 | + * Input: word = "leet1234code234" |
| 28 | + * Output: 2 |
| 29 | + * |
| 30 | + * Example 3: |
| 31 | + * |
| 32 | + * Input: word = "a1b01c001" |
| 33 | + * Output: 1 |
| 34 | + * Explanation: The three integers "1", "01", and "001" all represent the same integer because |
| 35 | + * the leading zeros are ignored when comparing their decimal values. |
| 36 | + * |
| 37 | + * Constraints: |
| 38 | + * |
| 39 | + * 1 <= word.length <= 1000 |
| 40 | + * word consists of digits and lowercase English letters. |
| 41 | + ******************************************************************************************************/ |
| 42 | + |
| 43 | +class Solution { |
| 44 | +private: |
| 45 | + bool isNumber(char ch) { |
| 46 | + return (ch >='0' && ch <='9'); |
| 47 | + } |
| 48 | + |
| 49 | +public: |
| 50 | + int numDifferentIntegers(string word) { |
| 51 | + word.push_back('z'); // add a char for edge case. |
| 52 | + bool intStart = false; // a stat for control |
| 53 | + int start = 0, len = 0; |
| 54 | + unordered_map<string, bool> stat; |
| 55 | + for(int i=0; i<word.size(); i++) { |
| 56 | + if (!isNumber(word[i]) ) { |
| 57 | + if (intStart) { |
| 58 | + while(word[start]=='0') { |
| 59 | + start++, len--; |
| 60 | + } |
| 61 | + stat[word.substr(start, len)] = true; |
| 62 | + intStart=false; |
| 63 | + } |
| 64 | + continue; |
| 65 | + } |
| 66 | + |
| 67 | + if (intStart == false) { |
| 68 | + intStart = true; |
| 69 | + start = i; |
| 70 | + len = 1; |
| 71 | + }else { |
| 72 | + len++; |
| 73 | + } |
| 74 | + } |
| 75 | + return stat.size(); |
| 76 | + } |
| 77 | +}; |
0 commit comments