LeetCode 821. Shortest Distance to a Character
Posted SomnusMistletoe
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 821. Shortest Distance to a Character相关的知识,希望对你有一定的参考价值。
题意:给定一个小写字符串以及一个在小写字符串中的字母,字符串长度为[1, 10000]。返回字符串中每个字母离给定字母的最短距离序列。
举例:
Input: S = "loveleetcode", C = ‘e‘
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
分析:对于每个字母,分别预处理它左边和右边离其最近的给定字母的下标,最后取最小值即可。
class Solution { public: vector<int> shortestToChar(string S, char C) { const int MAXN = 10000 + 10; int left[MAXN], right[MAXN]; memset(left, -1, sizeof left); memset(right, -1, sizeof right); int len = S.size(); int tmp = -1; for(int i = 0; i < len; ++i){ if(S[i] == C) tmp = i; left[i] = tmp; } tmp = -1; for(int i = len - 1; i >= 0; --i){ if(S[i] == C) tmp = i; right[i] = tmp; } vector<int> ans; for(int i = 0; i < len; ++i){ int tmpl, tmpr; if(left[i] != -1) tmpl = i - left[i]; else tmpl = len; if(right[i] != -1) tmpr = right[i] - i; else tmpr = len; ans.push_back(min(tmpl, tmpr)); } return ans; } };
以上是关于LeetCode 821. Shortest Distance to a Character的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode&Python] Problem 821. Shortest Distance to a Character
LeetCode 821. Shortest Distance to a Character
821. Shortest Distance to a Character
[Solution] 821. Shortest Distance to a Character