给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
思路一:字符串为s,vector<char>容器
从第一个字符开始放入vector容器里边,看第二个字符是否在容器里边,没有的话就放入容器继续往下查,有的话就停止此次查找,返回容器中字符数量。
函数:bool find(string s,char a)找到字符串s中是否有字符a,有返回false,没有返回true。
bool find(vector<char> s, char a)
{
for (auto it = s.begin(); it != s.end(); it++)
{
if ((*it) == a)
return true;
else
continue;
}
return false;
}
字符串查找一次就删除首元素一次
函数:string deletestr(string s)删除字符串首元素,
查找完整个字符串即应该有一个循环或者递归函数。
bool find(vector<char> s,char a)
{
for(auto it = s.begin();it!=s.end();it++)
}
思路一C++代码实现:(此方法有字符数限制)
class Solution {
public:
int lengthOfLongestSubstring(string s)
{
if (s == "")
return 0;
vector<char> ch1;
vector<int> length;//每个子串的长度
while (!s.empty())
{
bool bf = false;
for (auto it = s.begin(); it != s.end(); ++it)
{//此循环为找到每一个子串的长度
for (auto itt = ch1.begin(); itt != ch1.end(); itt++)
{//此循环查找ch1中是否有元素*it;
//cout << *itt << endl;
if ((*itt) == *it)
{
bf = true;
break;
}
}
if (!bf)//查找字符是否在ch1里边
ch1.push_back(*it);
//cout << " "<<ch1.size() <<endl;
}
length.push_back(ch1.size());
ch1.clear();
s.erase(s.begin());
}
int changdu = -100;
vector<int>::iterator it = length.begin();
while (it != length.end())
{
if ((*it) > changdu)
changdu = (*it);
it++;
}
return changdu;//return max(length);
}
};
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class fun
{
public:
bool find(vector<char> s, char a)
{
for (auto it = s.begin(); it != s.end(); it++)
if ((*it) == a)
return true;
return false;
}
int max(vector<int> length)
{
int changdu = -100;
vector<int>::iterator it = length.begin();
while (it != length.end())
{
if ((*it) > changdu)
changdu = (*it);
it++;
}
return changdu;
}
int lengthOfLongestSubstring(string s)
{
if (s == "")
return 0;
vector<char> ch1;
vector<int> length;//每个子串的长度
while (!s.empty())
{
bool bf = false;
for (auto it = s.begin(); it != s.end(); ++it)
{//此循环为找到每一个子串的长度
for (auto itt = ch1.begin(); itt != ch1.end(); itt++)
{//此循环查找ch1中是否有元素*it;
cout << *itt << endl;
if ((*itt) == *it)
{
bf = true;
break;
}
}
if (!bf)//查找字符是否在ch1里边
ch1.push_back(*it);
//cout << " "<<ch1.size() <<endl;
}
length.push_back(ch1.size());
ch1.clear();
s.erase(s.begin());
}
int changdu = -100;
vector<int>::iterator it = length.begin();
while (it != length.end())
{
if ((*it) > changdu)
changdu = (*it);
it++;
}
return changdu;//return max(length);
}
};
int main()
{
//vector<char> s = { 'a', 'b', 'c', 'd', 'a', 'b' };
string a("aa");
fun f;
//f.lengthOfLongestSubstring(a);
cout << f.lengthOfLongestSubstring(a) << endl;
return 0;
}
思路二: