52
52
53
53
<!-- 这里可写通用的实现逻辑 -->
54
54
55
- 将 ` word ` 按照字母切分,得到数字数组 ` nums ` ,然后利用 set 去重,返回 set 的长度即可。
55
+ ** 方法一:双指针 + 模拟**
56
+
57
+ 遍历字符串,找到每个整数的起始位置和结束位置,截取出这一个子串,将其存入哈希表 ` s ` 中。
58
+
59
+ 最后返回哈希表 ` s ` 的大小即可。
60
+
61
+ 注意,这里要去掉整数的前导零,并且不能直接将字符串转为整数,因为整数可能很大,超出 ` int ` 的范围。
62
+
63
+ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 ` word ` 的长度。
56
64
57
65
<!-- tabs:start -->
58
66
61
69
<!-- 这里可写当前语言的特殊实现逻辑 -->
62
70
63
71
``` python
64
- import re
65
-
66
-
67
72
class Solution :
68
73
def numDifferentIntegers (self , word : str ) -> int :
69
- nums = re.split(r ' [a-z ]+ ' , word)
70
- return len ({int (num) for num in nums if num != ' ' })
74
+ s = set ()
75
+ i, n = 0 , len (word)
76
+ while i < n:
77
+ if word[i].isdigit():
78
+ while i < n and word[i] == ' 0' :
79
+ i += 1
80
+ j = i
81
+ while j < n and word[j].isdigit():
82
+ j += 1
83
+ s.add(word[i: j])
84
+ i = j
85
+ i += 1
86
+ return len (s)
71
87
```
72
88
73
89
### ** Java**
@@ -77,20 +93,72 @@ class Solution:
77
93
``` java
78
94
class Solution {
79
95
public int numDifferentIntegers (String word ) {
80
- String [] nums = word. split(" [a-z]+" );
81
- Set<String > numSet = new HashSet<> ();
82
- for (String num : nums) {
83
- if (" " . equals(num)) {
84
- continue ;
96
+ Set<String > s = new HashSet<> ();
97
+ int n = word. length();
98
+ for (int i = 0 ; i < n; ++ i) {
99
+ if (Character . isDigit(word. charAt(i))) {
100
+ while (i < n && word. charAt(i) == ' 0' ) {
101
+ ++ i;
102
+ }
103
+ int j = i;
104
+ while (j < n && Character . isDigit(word. charAt(j))) {
105
+ ++ j;
106
+ }
107
+ s. add(word. substring(i, j));
108
+ i = j;
85
109
}
86
- int j = 0 ;
87
- while (j < num. length() - 1 && num. charAt(j) == ' 0' ) {
88
- ++ j;
110
+ }
111
+ return s. size();
112
+ }
113
+ }
114
+ ```
115
+
116
+ ### ** C++**
117
+
118
+ ``` cpp
119
+ class Solution {
120
+ public:
121
+ int numDifferentIntegers(string word) {
122
+ unordered_set<string > s;
123
+ int n = word.size();
124
+ for (int i = 0; i < n; ++i) {
125
+ if (isdigit(word[ i] )) {
126
+ while (i < n && word[ i] == '0') {
127
+ ++i;
128
+ }
129
+ int j = i;
130
+ while (j < n && isdigit(word[ j] )) {
131
+ ++j;
132
+ }
133
+ s.insert(word.substr(i, j - i));
134
+ i = j;
89
135
}
90
- numSet. add(num. substring(j));
91
136
}
92
- return numSet . size();
137
+ return s .size();
93
138
}
139
+ };
140
+ ```
141
+
142
+ ### **Go**
143
+
144
+ ```go
145
+ func numDifferentIntegers(word string) int {
146
+ s := map[string]struct{}{}
147
+ n := len(word)
148
+ for i := 0; i < n; i++ {
149
+ if word[i] >= '0' && word[i] <= '9' {
150
+ for i < n && word[i] == '0' {
151
+ i++
152
+ }
153
+ j := i
154
+ for j < n && word[j] >= '0' && word[j] <= '9' {
155
+ j++
156
+ }
157
+ s[word[i:j]] = struct{}{}
158
+ i = j
159
+ }
160
+ }
161
+ return len(s)
94
162
}
95
163
```
96
164
0 commit comments