classSolution: defuniqueLetterString(self, s: str) -> int: index = collections.defaultdict(list) for i, c inenumerate(s): index[c].append(i)
res = 0 for arr in index.values(): arr = [-1] + arr + [len(s)] for i inrange(1, len(arr) - 1): res += (arr[i] - arr[i - 1]) * (arr[i + 1] - arr[i]) return res
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: intuniqueLetterString(string s){ unordered_map<char, vector<int>> index; for (int i = 0; i < s.size(); i++) { index[s[i]].emplace_back(i); } int res = 0; for (auto &&[_, arr]: index) { arr.insert(arr.begin(), -1); arr.emplace_back(s.size()); for (int i = 1; i < arr.size() - 1; i++) { res += (arr[i] - arr[i - 1]) * (arr[i + 1] - arr[i]); } } return res; } };
intuniqueLetterString(char * s){ structListNode **index = (struct ListNode **)malloc(sizeof(struct ListNode *) * 26); for (int i = 0; i < 26; i++) { index[i] = NULL; } int len = strlen(s); for (int i = 0; i < len; i++) { structListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode)); node->val = i; node->next = index[s[i] - 'A']; index[s[i] - 'A'] = node; } int res = 0; for (int i = 0; i < 26; i++) { if (index[i]) { structListNode *curr = index[i]; structListNode *prev =NULL; structListNode *next = curr->next; while (curr) { if (prev == NULL && next == NULL) { res += (curr->val + 1) * (len - curr->val); } elseif (prev == NULL) { res += (curr->val - next->val) * (len - curr->val); } elseif (next == NULL) { res += (curr->val + 1) * (prev->val - curr->val); } else { res += (curr->val - next->val) * (prev->val - curr->val); } prev = curr; curr = curr->next; if (next) { next = next->next; } } } } for (int i = 0; i < 26; i++) { if (index[i]) { structListNode *curr =NULL, *tmp = NULL; for (curr = index[i]; curr; ) { tmp = curr; curr = curr->next; free(tmp); } } } return res; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
var uniqueLetterString = function(s) { const index = newMap(); for (let i = 0; i < s.length; i++) { const c = s[i]; if (!index.has(c)) { index.set(c, []); index.get(c).push(-1); } index.get(c).push(i); } let res = 0; for (const [_, arr] of index.entries()) { arr.push(s.length); for (let i = 1; i < arr.length - 1; i++) { res += (arr[i] - arr[i - 1]) * (arr[i + 1] - arr[i]); } } return res; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13
funcuniqueLetterString(s string) (ans int) { idx := map[rune][]int{} for i, c := range s { idx[c] = append(idx[c], i) } for _, arr := range idx { arr = append(append([]int{-1}, arr...), len(s)) for i := 1; i < len(arr)-1; i++ { ans += (arr[i] - arr[i-1]) * (arr[i+1] - arr[i]) } } return }