超时解法1:过了32个测试用例
class Solution {
public:
int uniqueLetterString(string S)
{
int ans = S.length(), len = 2, begin = 0;
while (len<=S.length())
{
if (begin+len<=S.length())
{
ans += cnt(S, len, begin);
begin++;
}
else
{
len++;
begin = 0;
}
}
return ans;
}
int cnt(string s, int len,int begin)
{
int ans = 0;
map<char, int> count;
for (int i = begin; i <begin+len; i++)
{
if (count[s[i]] == 0)
{
ans++;
}
else if(count[s[i]]==1)
{
ans--;
}
count[s[i]]++;
}
return ans;
}
};
超时解法2:过了62个测试用例,卡在的最后一个了
两层for循环,第一层for遍历整个字符串,第二层以i为起点遍历整个字符串,直到所有的字母都出现过。
map容器只要新出现的字符,自动赋值为0,size增加1;
class Solution {
public:
int uniqueLetterString(string S)
{
// char buffer[_MAX_PATH];
// _getcwd(buffer, _MAX_PATH);
// string n = buffer;
// n += "\\2.1.txt";
// ofstream out;
// out.open(n, ios::app);
// if (!out)
// {
// return 0;
// }
int ans = 0, len = 0, begin = 0 ;
int s = pow(10, 9) + 7;
for (int i = 0; i < S.length(); i++)
{
map<char,int> te;
int num = 0;
int j = i;
for (j; j < S.length(); j++)
{
//cout << S.substr(i, j - i + 1) << endl;
if (te[S[j]] == 1)
len++;
if (len == 26)
{
break;
}
te[S[j]]++;
ans += te.size() - len;
}
len = 0;
//out << i << " " << ans << "\n";
//system("cls");
}
return ans;
}
};
网上解法:LeeCode 828. Unique Letter String
class Solution {
public:
int uniqueLetterString(string S) {
vector<int> pos[26];
for (int i = 0; i < 26; i++) {
pos[i].push_back(-1);//把边界加入,便于计算
pos[i].push_back(S.size());//把边界加入,便于计算
}
for (int i = 0; i < S.size(); i++) {
pos[S[i] - 'A'].push_back(i);
}
int ans = 0;
for (int i = 0; i < 26; i++) {
sort(pos[i].begin(), pos[i].end());
for (int j = 1; j < pos[i].size() - 1; j++) {
ans += (pos[i][j + 1] - pos[i][j]) * (pos[i][j] - pos[i][j - 1]);
}
}
return ans;
}
};