+{"link": "https://leetcode.com/problems/shortest-distance-to-a-character", "name": "Shortest Distance to a Character", "difficulty": "Easy", "statement": "<div><p>Given a string <code>S</code> and a character <code>C</code>, return an array of integers representing the shortest distance from the character <code>C</code> in the string.</p>\n\n<p><strong>Example 1:</strong></p>\n\n<pre><strong>Input:</strong> S = \"loveleetcode\", C = 'e'\n<strong>Output:</strong> [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]\n</pre>\n\n<p> </p>\n\n<p><strong>Note:</strong></p>\n\n<ol>\n\t<li><code>S</code> string length is in <code>[1, 10000].</code></li>\n\t<li><code>C</code> is a single character, and guaranteed to be in string <code>S</code>.</li>\n\t<li>All letters in <code>S</code> and <code>C</code> are lowercase.</li>\n</ol>\n</div>", "language": "cpp", "solution": "#include <iostream>\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nclass Solution\n{\npublic:\n vector<int> shortestToChar(string S, char C)\n {\n vector<int> poss;\n int n = S.length();\n for (int i = 0; i < n; i++)\n {\n if (S[i] == C)\n {\n poss.push_back(i);\n }\n }\n\n vector<int> out;\n\n int occ = poss.size();\n\n if (occ)\n {\n for (int i = 0; i <= poss[0]; ++i)\n out.push_back(poss[0] - i);\n }\n for (int i = 0; i < occ - 1; i++)\n {\n for (int j = poss[i] + 1; j <= poss[i + 1]; ++j)\n {\n out.push_back(min((j - poss[i]), (poss[i + 1] - j)));\n }\n }\n\n if (occ)\n {\n for (int i = poss[occ - 1] + 1; i < n; ++i)\n out.push_back(i - poss[occ - 1]);\n }\n\n return out;\n }\n};"}
0 commit comments