given a str find the length of the longest substring that contains no repeated characters code example
Example 1: Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string. javascript
class Solution {
public:
vector<int> shortestToChar(string S, char C) {
vector<int> r(S.size(), 0);
int prev = -S.size();
for (int i = 0; i < S.size(); ++ i) {
if (S[i] == C) prev = i;
r[i] = i - prev;
}
prev = INT_MAX;
for (int i = S.size() - 1; i >= 0; -- i) {
if (S[i] == C) prev = i;
r[i] = min(r[i], prev - i);
}
return r;
}
};
Example 2: Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string. javascript
class Solution {
public:
vector<int> shortestToChar(string S, char C) {
int n = S.size();
vector<int> r(n, n);
for (int i = 0; i < n; ++ i) {
if (S[i] == C) r[i] = 0;
}
for (int i = 1; i < n; ++ i) {
r[i] = min(r[i], r[i - 1] + 1);
}
for (int i = n - 2; i >= 0; -- i) {
r[i] = min(r[i], r[i + 1] + 1);
}
return r;
}
};