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

来源:互联网 发布:如何评价赵薇事件 知乎 编辑:程序博客网 时间:2024/04/24 08:03

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 0
原创粉丝点击