對(duì)稱子字符串

對(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;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容