对称子字符串
Description
Given a string ‘str’ of digits, find length of the longest substring of ‘str’, such that the length of the substring is 2k digits and sum of left k digits is equal to the sum of right k digits.
给定一个数字字符串' str ',找出' str '的最长子串的长度,使该子串的长度为2k,且左k位数字的和等于右k位数字的和。
Input
输入第一行是测试用例的个数,后面每一行表示一个数字组成的字符串,例如:"123123"
Output
输出找到的满足要求的最长子串的长度。例如,给定的例子长度应该是 6。每行对应一个用例的结果。
Sample Input
1
1538023
Sample Output
4
Solution
public class SymmetricalSubstr {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int caseNum = in.nextInt();
for(int i = 0; i < caseNum; i++){
in.nextLine();
String str = in.next();
System.out.println(getLongestLen(str));
}
}
public static int getLongestLen(String str){
int max = 0;
int strLen = str.length();
for(int i = 0; i < strLen - 1; i++){
int left = i;
int right = i + 1;
int leftSum = 0;
int rightSum = 0;
while(left >= 0 && right < strLen){
leftSum += str.charAt(left) - '0';
rightSum += str.charAt(right) - '0';
if(leftSum == rightSum){
max = Math.max(max, right - left + 1);
}
left--;
right++;
}
}
return max;
}
}