对称子字符串

对称子字符串

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;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容