字符串运用-密码截取-对称

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

输入描述:
输入一个字符串

输出描述:

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

思路一:

import java.util.Scanner;

public class Main
{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext())
        {
            String str = scanner.next();
            int max = 1;
            for (int i = 1; i < str.length() - 1; i++)
            {
                int m = i - 1;
                int n = i + 1;
                int count = 0;
                while (m >= 0 && n < str.length())
                {
                    if (str.charAt(m) == str.charAt(n))
                    {
                        count++;
                        m--;
                        n++;
                    }
                    else
                        break;
                }
                max = max >= (count * 2 + 1) ? max : (count * 2 + 1);
            }
            for (int i = 1; i < str.length(); i++)
            {
                int m = i - 1;
                int n = i;
                int count = 0;
                while (m >= 0 && n < str.length())
                {
                    if (str.charAt(m) == str.charAt(n))
                    {
                        count++;
                        m--;
                        n++;
                    }
                    else
                        break;
                }
                max = max >= (count * 2) ? max : (count * 2);
            }
            System.out.println(max);
        }
    }
}

思路二:

import java.util.Scanner;

public class Main
{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext())
        {
            String str = scanner.next();
            StringBuffer sb = new StringBuffer(str);
            String rev = sb.reverse().toString();
            System.out.println(getMax(str, rev));
        }
    }
    public static int getMax(String str, String rev)
    {
        for (int len = str.length(); len >= 1; len--)
        {
            for (int i = 0; i <= str.length() - len; i++)
            {
                String sub = rev.substring(i, i + len);
                if (str.contains(sub))
                    return len;
            }
        }
        return 1;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值