我们规定对一个字符串的shift操作如下:

shift(“ABCD”,0)=”ABCD”
shift(“ABCD”,1)=”DABC”
shift(“ABCD”,2)=”CDAB”
换言之,我们把最左侧的N个字符剪切下来,按序附加到了右侧。
给定一个长为n的字符串,我们规定最多可以进行n次向左的循环shift操作。如果
shift(string,x)=string(0<=x< n),
我们称其为一次匹配(match)。求在shift过程中出现匹配的次数。


好了,题目叙述完毕

解题思路:
这里用了简单粗暴的方法,定义一个交换函数,进行按题所示的’shift’操作,把所有的结果记录在HashMap中,对应的value记录的是该字符串出现的次数,并在ArrayList中也记录一次,用于在最后的在Map中查找出现次数的依据。
代码如下:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;


public class Main {

    public static void main(String[] args) {
        Main ss=new Main();
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入字符串:");
        String s=sc.nextLine();//从键盘读取要处理的字符串
        int max=0;//匹配次数
        HashMap<String,Integer>hm=new HashMap<String,Integer>();
        ArrayList<String>list=new ArrayList<String>();
        for(int i=0;i<s.length();i++)
        {
            String temp=ss.swap(s, i);
            if(hm.containsKey(temp)){//如果map中已经包含该单词,则将其个数+1
                 int x = hm.get(temp);
                 x++;
                 hm.put(temp, x);
             }else{  //如果map中没用包含该单词,代表该单词第一次出现,则将其放入map并将个数设置为1
                 hm.put(temp, 1);
                 list.add(temp);
             }

        }
        for(String xx:list)//对字符串所有可能出现的左移效果进行遍历,记录最大匹配次数
        {
            int i=hm.get(xx);
            if(i>max)
                max=i;

        }

        System.out.println(max);
        sc.close();//关闭流

    }



    public String swap(String str,int num)//把一个字符串按题目要求左移并返回
    {

        String s1=str.substring(num, str.length());
        StringBuffer result=new StringBuffer(s1);
        result.append(str.substring(0, num));
        return result.toString();
    }
}

按照题示,输入byebyebye,输出3
这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值