1 题目描述:
Consider the string s to be the infinite wraparound string of “abcdefghijklmnopqrstuvwxyz”, so s will look like this: “…zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd….”.
Now we have another string p. Your job is to find out how many unique non-empty substrings of p are present in s. In particular, your input is the string p and you need to output the number of different non-empty substrings of p in the string s.
Note: p consists of only lowercase English letters and the size of p might be over 10000.
我的理解:给定字符串p,求解p中在s(无限循环字母表…zabc….xyzabc..)中出现的不重复的子字符串的个数。
language:C++
2 我的错误解答1:求得字符串中的子字符串的个数:
class Solution {
public:
int findSubstringInWraproundString(string p) {
//permutation and combination
int n = p.size();//or int = p.length()
int sum = (1 + n) * n / 2;
//get rid of repetitive strings
int m = n;
//for the sole letter
for(int i = 0; i < n; ++i)
{
for(int j = i + 1; j < n; ++j)
{
if(p[i]==p[j])
{
sum--;
m--;
//for string consists of more than 1 letter
for(int k = 1; k < (n-i); ++k)
{
if( (j+k)<m )
{
std::string root=p.substr(i,k);
std::string comp=p.substr(j,k);
if(root.compare(comp))
{
sum--;
}
}
}
}
}
}
return sum;
}
};
3 我的解答2:结果正确但是运行时间超出限制:
//结果正确,但是运行时间超出限制:
int findSubstringInWraproundString2(std::string p){
int n = p.size();//or int = p.length()
if(n<=1)
{
return n;
}
int sum = 0;
//统计数据中不同元素的个数
std::vector<char> uniqe_char;
uniqe_char.push_back(p[0]);
for(int i = 0; i < n; ++i)
{
char temp_c=p[i];
std::vector<char>::iterator c_iter=uniqe_char.begin();
for(; c_iter!=uniqe_char.end(); ++c_iter)
{
if(*c_iter == temp_c)
{
break;
}
}
if(c_iter == uniqe_char.end())
{
uniqe_char.push_back(temp_c);
}
}
sum = uniqe_char.size();
//
std::vector<std::string> total_string;
for (int i = 0; i < n-1; ++i) {
char temp_c=p[i];
int flag=0;
for (int j = i+1; j < n; ++j) {
if((p[j]-temp_c)==1)
{
flag++;
std::string this_str=p.substr(i,flag);
total_string.push_back(this_str);
temp_c=p[j];
} else{
if((p[j]=='a') && (p[j]-temp_c)==(-25))
{
flag++;
std::string this_str=p.substr(i,flag);
total_string.push_back(this_str);
temp_c=p[j];
} else{
break;
}
}
}
}
std::vector<std::string> uniqe_string;
int uniqe_str_sum=0;
if (total_string.size()<=1)
{
uniqe_str_sum=total_string.size();
}
else
{
uniqe_string.push_back(total_string[0]);
//
for (int i = 0; i < total_string.size() ; ++i)
{
std::string temp_str=total_string[i];
std::vector<std::string>::iterator str_iter=uniqe_string.begin();
for(; str_iter!=uniqe_string.end(); ++str_iter)
{
if(*str_iter == temp_str)
{
break;
}
}
if(str_iter == uniqe_string.end())
{
uniqe_string.push_back(temp_str);
}
}
uniqe_str_sum = uniqe_string.size();
}
sum += uniqe_str_sum;
return sum;
}