要在C ++中找到在左侧和右侧具有相等和的最长子串 [英] To find the longest substring with equal sum in left and right in C++
问题描述
我正在解决一个问题,我遇到了一些问题:
I was solving a question, with which I am having some problems:
完成函数getEqualSumSubstring,单个参数是一个字符串
s
,它只包含非零数字。
此函数应打印s
的最长连续子字符串的长度,使得子字符串的长度为2 * N个数字,并且最左边N个数字等于最右边N个数字的和。如果没有这样的字符串,你的函数应该打印0。
Complete the function getEqualSumSubstring, which takes a single argument. The single argument is a string
s
, which contains only non-zero digits. This function should print the length of longest contiguous substring ofs
, such that the length of the substring is 2*N digits and the sum of the leftmost N digits is equal to the sum of the rightmost N digits. If there is no such string, your function should print 0.
int getEqualSumSubstring(string s) {
int i=0,j=i,foundLength=0;
for(i=0;i<s.length();i++)
{
for(j=i;j<s.length();j++)
{
int temp = j-i;
if(temp%2==0)
{
int leftSum=0,rightSum=0;
string tempString=s.substr(i,temp);
for(int k=0;k<temp/2;k++)
{
leftSum=leftSum+tempString[k]-'0';
rightSum=rightSum+tempString[k+(temp/2)]-'0';
}
if((leftSum==rightSum)&&(leftSum!=0))
if(s.length()>foundLength)
foundLength=s.length();
}
}
}
return(foundLength);
}
问题是,此代码适用于一些示例,不为其他人。因为这是一个考试类型问题,我没有测试用例。
The problem is that this code is working for some samples and not for the others. Since this is an exam type question I don't have the test cases either.
推荐答案
b
$ b
This code works
int getEqualSumSubstring(string s) {
int i=0,j=i,foundLength=0;
for(i=0;i<s.length();i++)
{
for(j=i;j<s.length();j++)
{
int temp = j-i+1;
if(temp%2==0)
{
int leftSum=0,rightSum=0;
string tempString=s.substr(i,temp);
// printf("%d ",tempString.length());
for(int k=0;k<temp/2;k++)
{
leftSum=leftSum+tempString[k]-48;
rightSum=rightSum+tempString[k+(temp/2)]-48;
}
if((leftSum==rightSum)&&(leftSum!=0))
if(tempString.length()>foundLength)
foundLength=tempString.length();
}
}
}
return(foundLength);
}
temp变量必须是j-i + 1。否则,整个字符串是答案的情况将不会被覆盖。此外,我们需要进行Scott建议的更改。
The temp variable must be j-i+1. Otherwise the case where the whole string is the answer will not be covered. Also, we need to make the change suggested by Scott.
这篇关于要在C ++中找到在左侧和右侧具有相等和的最长子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!