【Leetcode_easy】821. Shortest Distance to a Character
problem
821. Shortest Distance to a Character
solution1:
class Solution { public: vector<int> shortestToChar(string S, char C) { int n = S.size(); vector<int> res(n, n); for(int i=0; i<n; ++i) if(S[i]==C) res[i] = 0; for(int i=1; i<n; ++i) res[i] = min(res[i], abs(res[i-1]+1)); for(int i=n-2; i>=0; --i) res[i] = min(res[i], abs(res[i+1]+1)); return res; } };
solution2:
class Solution { public: vector<int> shortestToChar(string S, char C) { int n = S.size(); vector<int> res(n, n); int pos = -n;//errr... for(int i=0; i<n; ++i) { if(S[i]==C) pos = i; res[i] = min(res[i], abs(i-pos)); } for(int i=n-1; i>=0; --i) { if(S[i]==C) pos = i; res[i] = min(res[i], abs(i-pos)); } return res; } };
参考
1. Leetcode_easy_821. Shortest Distance to a Character;
2. Discuss;
3. grandyang;
完
各美其美,美美与共,不和他人作比较,不对他人有期待,不批判他人,不钻牛角尖。
心正意诚,做自己该做的事情,做自己喜欢做的事情,安静做一枚有思想的技术媛。
版权声明,转载请注明出处:https://www.cnblogs.com/happyamyhope/
心正意诚,做自己该做的事情,做自己喜欢做的事情,安静做一枚有思想的技术媛。
版权声明,转载请注明出处:https://www.cnblogs.com/happyamyhope/