3817. Good Indices in a Digit String 🔒
题目描述
You are given a string s consisting of digits.
An index i is called good if there exists a substring of s that ends at index i and is equal to the decimal representation of i.
Return an integer array of all good indices in increasing order.
Example 1:
Input: s = "0234567890112"
Output: [0,11,12]
Explanation:
-
At index 0, the decimal representation of the index is
"0". The substrings[0]is"0", which matches, so index0is good. -
At index 11, the decimal representation is
"11". The substrings[10..11]is"11", which matches, so index11is good. -
At index 12, the decimal representation is
"12". The substrings[11..12]is"12", which matches, so index12is good.
No other index has a substring ending at it that equals its decimal representation. Therefore, the answer is [0, 11, 12].
Example 2:
Input: s = "01234"
Output: [0,1,2,3,4]
Explanation:
For every index i from 0 to 4, the decimal representation of i is a single digit, and the substring s[i] matches that digit.
Therefore, a valid substring ending at each index exists, making all indices good.
Example 3:
Input: s = "12345"
Output: []
Explanation:
No index has a substring ending at it that matches its decimal representation.
Therefore, there are no good indices and the result is an empty array.
Constraints:
1 <= s.length <= 105sonly consists of digits from'0'to'9'.
解法
方法一:模拟
我们注意到,字符串 \(s\) 的长度最大为 \(10^5\),而索引 \(i\) 的十进制表示的长度最多为 \(6\)(因为 \(10^5\) 的十进制表示为 \(100000\),长度为 \(6\))。因此,我们只需要检查每个索引 \(i\) 的十进制表示对应的子串是否与之相等。
时间复杂度 \(O(n)\),其中 \(n\) 是字符串 \(s\) 的长度。忽略答案的空间消耗,空间复杂度 \(O(1)\)。
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 5 6 7 8 9 10 11 | |