问题描述:
散散的手链沿两个方向反转复制,AB 可变成ABBA/BAAB。
输入现在的字符串序列(ABBAABBA)
输出至少需要几个珠子(2)
#include<iostream>
#include<string>
#include<numeric>
using namespace std;
string GetResult(string s)
{
int num = 0;
int length = s.length();
int begin = 0;
int end = length - 1;
int mid = end;
cout << "111"<<endl;
string sCur;
while (s[begin] == s[mid])
{
end = mid;
mid = (begin + end - 1) / 2;
sCur = s.substr(0, mid+1);
if (end - begin == 1)
{
return sCur;
break;
}
}
cout << sCur.length() << endl;
return sCur;
}
int main()
{
string res;
string _s="ABBAABBA";
cout << _s << endl;
res = GetResult(_s);
cout << res << endl;
system("pause");
return 0;
}
运行结果:
虽然现在能出来结果,还是怪怪的,但当函数中的两个无关紧要的cout语句删除后,程序马上就有如下error,还没有找到原因,我明明是有返回值的呀!希望大佬能发现小菜鸟的问题,感激不尽,┭┮﹏┭┮
终于改好啦,正确代码看这里
#include<iostream>
#include<string>
#include<numeric>
using namespace std;
string GetResult(string s)
{
int begin = 0;
int end = s.length() - 1;
int mid;
string sCur;
while (s[begin] == s[end])
{
mid = (begin + end - 1) / 2;
end = mid;
sCur = s.substr(begin, mid+1);
if (end - begin == 1)
{
return sCur;
}
}
return sCur;
}
int main()
{
string res;
string _s="ABBAABBA";
cout << _s << endl;
res = GetResult(_s);
cout << res.length() << endl;
cout <<res << endl;
system("pause");
return 0;
}
完工!