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

题目描述:

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

Java实现:

import java.util.*;

public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String str = sc.nextLine();
            int res = process1(str);
            System.out.println(res);
        }
    }
    
    private static int process1(String str) {
        int len = str.length();
        int max = 1;//最长回文子串的长度
        //以当前字符为中心,即奇数个
       
        for (int i = 1; i < len-1; i++) {
            int l = i-1, r = i+1;
            int count = 0;
            while (l>=0 && r < len) {
                if (str.charAt(l--) == str.charAt(r++))
                    count++;
                else
                    break;
            }
            max = Math.max(max, 2*count+1);
        }
        //以空隙为中心,即偶数个
        for (int i = 1; i < len-1; i++) {
            int l = i-1, r = i;
            int count = 0;
            while (l>=0 && r < len) {
                if (str.charAt(l--) == str.charAt(r++))
                    count++;
                else
                    break;
            }
            max = Math.max(max, 2*count);
        }
        return max;
    }
}

知识点:

  • 方法1是如上面代码所示,以每个字符或者空隙为中心,同时往左右找,时间复杂度为O(n^2)
  • TODO:方法2,动态规划
  • TODO:方法3,颠倒字符串,求两个字符串的最长公共子串
  • TODO:方法3,manacher算法

猜你喜欢

转载自blog.csdn.net/heyiamcoming/article/details/80695935