这是leetcode上面的第三题,我想使用《算法导论》的求最大子数组的方法来求解,貌似递归不能停下来,导致segmentation fault

AdairJun 2015-02-12 06:23:24
#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;
}

...全文
182 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
fly_dragon_fly 2015-02-13
  • 打赏
  • 举报
回复
应该是一定停不下来吧, 你的递归终止条件是x==0&&y==0,而在这个调用 int right_res=length(s,p,y); 这个y没有改变,永远不可能到0

64,642

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧