这是leetcode上面的第三题,我想使用《算法导论》的求最大子数组的方法来求解,貌似递归不能停下来,导致segmentation fault
#include <iostream>
#include <string>
using namespace std;
class Solution
{
private:
int max(const int& x,const int& y)
{
return x > y ? x : y;
}
int cross_length(const string& s,const int& low,const int& middle,const int& high)
{
string substring="";
substring.push_back(s[middle]);
auto i = middle;
while (i >=low)
{
--i;
if(substring.find(s[i]) != substring.npos) //如果在substring当中找到了s[i]
{
++i;
break;
}
else
substring.push_back(s[i]);
}
auto j = middle;
while (j <=high)
{
++j;
if(substring.find(s[j]) != substring.npos)
{
--j;
break;
}
else
substring.push_back(s[j]);
}
cout<<"substring is -------------"<<substring<<endl;
return j-i+1;
} int length(const string& s,const int& x,const int& y)
{
if (x==0 && y==0)
return 1;
int p = (x+y)/2;
cout<<"p is -------"<<p<<endl;
int cross_res=cross_length(s,x,p,y);
int left_res=length(s,x,p);
int right_res=length(s,p,y);
return max(max(left_res,right_res),cross_res);
}
public:
int lengthOfLongestSubstring(string s)
{
return length(s,0,s.length()-1);
}
};
int main(int argc,char** argv)
{
string s ="aabcabcbb";
cout<<s<<endl;
Solution solve;
int result = solve.lengthOfLongestSubstring(s);
cout<<"the result is -------------------------------"<<result<<endl;
return 0;
}