本文共 1092 字,大约阅读时间需要 3 分钟。
?????????????????????????????
last???????????????c?????????????????i????????????????prev???????(i - prev) * (n - i + 1)????????????
last??????????????????????26???26?????????-1?last???i????????????????prev???????(i - prev) * (n - i + 1)?#includeusing namespace std;int main() { char s[] = "abcdabca"; int n = strlen(s); int last[26] = {-1}; // ???????????? long long ans = 0; for (int i = 0; i < n; ++i) { char c = s[i]; int idx = c - 'a'; if (last[idx] != -1) { // ???? ans += (i - last[idx]) * (n - i + 1); } // ??????? last[idx] = i; } cout << ans << endl; return 0;}
last???????????????????????-1????????c??????idx?c???last?????????????????????last[idx]???????(i - last[idx]) * (n - i + 1)????ans??i???last[idx]?????????ans????????????O(n)??????????????
转载地址:http://siqq.baihongyu.com/