Longest Even Length Substring Solution in O(1) space
Problem: Find a longest substring which has sum of left elements from mid is equal to right element
Sol : Iterate over the string and check for midpoint (every) and create leftsum and rightsum variables to hold respective sum and check whether they are equal and if they are greater than maximum substring having same property
code :
import java.lang.*;
import java.io.*;
class GFG
{
public static int length(String str)
{
int len=str.length();
int length=0;
for(int i=0;i<=len-2;i++)
{
int left=i;
int right=i+1;
int leftsum,rightsum;
leftsum=rightsum=0;
while(right<len && left>=0)
{
leftsum+=str.charAt(left)-'0';
rightsum+=str.charAt(right)-'0';
if(leftsum==rightsum)
length=Math.max(length,right-left+1);
left--;
right++;
}
}
return length;
}
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
String str=ab.next();
System.out.println(length(str));
}
}
}
0 Comments:
Post a Comment