對(duì)稱子字符串
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.
給定一個(gè)數(shù)字字符串' str ',找出' str '的最長(zhǎng)子串的長(zhǎng)度,使該子串的長(zhǎng)度為2k,且左k位數(shù)字的和等于右k位數(shù)字的和。
Input
輸入第一行是測(cè)試用例的個(gè)數(shù),后面每一行表示一個(gè)數(shù)字組成的字符串,例如:"123123"
Output
輸出找到的滿足要求的最長(zhǎng)子串的長(zhǎng)度。例如,給定的例子長(zhǎng)度應(yīng)該是 6。每行對(duì)應(yīng)一個(gè)用例的結(jié)果。
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;
}
}