#include<bits/stdc++.h> using namespace std; class Solution{ public: int uniqueLetterString(string s){ const int constraint_length = s.size() + 10; const int ch_nums = 26; const int first_char = (int)'A'; // store the distance, first is the distance to the previous charactor, second is the distance to the next char pair<int,int> ch_dist[constraint_length]; //index store index from 1 int index[ch_nums] = {}; // try to find the distance for(int i = 0 ; i < s.size() ; i++){ const int word_th = s[i] - first_char; ch_dist[i + 1].first = i + 1 - index[word_th]; if(index[word_th] != 0) ch_dist[index[word_th]].second = i + 1 - index[word_th]; index[word_th] = i + 1; } for(int i = 0 ; i < ch_nums ; i++){ if(index[i]!=0){ ch_dist[index[i]].second = s.size() + 1 - index[i]; // cout<<i<<' '<<s.size()<<'+'<<1<<'-'<<index[i]<<'='<<s.size() + 1 - index[i]<<endl; } } for(int i = 1 ; i < s.size() + 1 ; i++){ // cout<< i<<' '<< ch_dist[i].first<< ' '<< ch_dist[i].second<<' '<<index[s[i-1]-'A']<<endl; } long long rlt = 0; for(int i = 1 ; i < s.size() + 1 ; i++){ rlt += ch_dist[i].first + ch_dist[i].second - 1; int pre, nxt; // if(i == ch_dist[i].first){ // pre = i - 1; // } // else{ // pre = i - ch_dist[i].first ; // } // if(i == index[s[i - 1]-'A']) // nxt = s.size() - i; // else // nxt = ch_dist[i].second ; pre = ch_dist[i].first - 1; nxt = ch_dist[i].second - 1; rlt += pre * nxt; // cout<<pre<<' '<<nxt<<endl; } return rlt ; } }; int main(){ Solution sol; string ex1 = "ABC"; cout<<ex1<<endl; cout<<sol.uniqueLetterString(ex1)<<endl; string ex2 = "ABA"; cout<<ex2<<endl; cout<<sol.uniqueLetterString(ex2)<<endl; string ex3 = "LEETCODE"; cout<<ex3<<endl; cout<<sol.uniqueLetterString(ex3)<<endl; string ex4 = "ABCD"; cout<<ex4<<endl; cout<<sol.uniqueLetterString(ex4)<<endl; string ex5 = "ABAC"; cout<<ex5<<endl; cout<<sol.uniqueLetterString(ex5)<<endl; string ex6 = "ABACA"; cout<<ex6<<endl; cout<<sol.uniqueLetterString(ex6)<<endl; return 0; }