Problem
题目大意:输出字符串的每个字符到一个指定字符的对短距离。
https://leetcode.com/problems/shortest-distance-to-a-character/description/
Given a string S
and a character C
, return an array of integers representing the shortest distance from the character C
in the string.
Example 1:
Input: S = "loveleetcode", C = 'e' Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
Note:
S
string length is in[1, 10000].
C
is a single character, and guaranteed to be in stringS
.- All letters in
S
andC
are lowercase.
Solution: Two Pass
Time complexity: O(n)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// Author: Huahua // Running time: 14 ms class Solution { public: vector<int> shortestToChar(string S, char C) { const int n = S.length(); vector<int> ans(n, INT_MAX); int index = -1; for (int i = 0; i < n; ++i) { if (S[i] == C) index = i; if (index < 0) continue; ans[i] = abs(i - index); } index = -1; for (int i = n - 1; i >= 0; --i) { if (S[i] == C) index = i; if (index < 0) continue; ans[i] = min(ans[i], abs(i - index)); } return ans; } }; |
V2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Author: Huahua // Running time: 14 ms class Solution { public: vector<int> shortestToChar(string S, char C) { const int n = S.length(); vector<int> indices(2 * n); // 0, 1, ..., n - 1, n - 1, n - 2, ..., 0 std::iota(indices.begin(), indices.begin() + n, 0); std::iota(indices.rbegin(), indices.rbegin() + n, 0); vector<int> ans(n, INT_MAX); int index = -n; for (int i : indices) { if (S[i] == C) index = i; ans[i] = min(ans[i], abs(i - index)); } return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment