华为机试------------------字符串运用-密码截取

题目描述

Catcher 是MCA国的情报员,他工作时发现敌国会用一些对称的密码进行通信,比如像这些ABBA,ABA,A,123321,但是他们有时会在开始或结束时加入一些无关的字符以防止别国破解。比如进行下列变化 ABBA->12ABBA,ABA->ABAKK,123321->51233214 。因为截获的串太长了,而且存在多种可能的情况(abaaab可看作是aba,或baaab的加密形式),Cathcer的工作量实在是太大了,他只能向电脑高手求助,你能帮Catcher找出最长的有效密码串吗?

(注意:记得加上while处理多个测试用例)

输入描述:

输入一个字符串

输出描述:

返回有效密码串的最大长度

输入

ABBA

输出

4
import java.util.Objects;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String password = scanner.nextLine();
            if(!(password==null || Objects.equals(password, "") )){
                System.out.println(findPassword(password));
            }

        }
    }

    /**
     *  遍历字符串
     *  如果当前字符只有一个,直接跳到下一个字符
     *  如果当前字符的最大下标差值小于maxLen,跳过(无意义,就算有回文,也一定小于最大)
     *  前后同时进行遍历子字符串,如果前后字符中有任何一位不相同,将lastIndex改变
     *  扔掉遍历过的字符串(使indexOf()起到作用)
     */
    private static int findPassword(String password) {
        int lenth = password.length();
        String pa = password;
        int maxLen = 1;
        for (int i = 0; i <= lenth - maxLen; i++) {
            char c = pa.charAt(i);
            int index = password.indexOf(c + "");
            int lastIndex = password.lastIndexOf(c + "");
            if (index == lastIndex) {//如果当前 char 只有一个的话,
                continue;
            }else if(lastIndex - index <= maxLen){
                continue;
            }else {
                while (index != lastIndex){
                    int len = 2;
                    int frontPoint = index + 1;
                    int rearPoint = lastIndex - 1;
                    while (frontPoint < rearPoint ) {
                        if(password.charAt(frontPoint) != password.charAt(rearPoint)){
                            len = -1;
                            break;
                        }
                        len += 2;
                        frontPoint++;
                        rearPoint--;
                    }
                    if (frontPoint == rearPoint) {
                        len++;
                    }
                    maxLen = maxLen > len ? maxLen : len;
                    lastIndex =  password.substring(0,lastIndex).lastIndexOf(c+"");
                }
            }
            password = password.substring(password.indexOf(c + "")+1);
        }
        return maxLen;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37961948/article/details/80508877