POJ 2406(KMP 算法的应用)

题目地址:http://acm.pku.edu.cn/JudgeOnline/problem?id=2406
题目要求一个串的最大重复次数:

abcd 1

aaaa 4

ababab 3

 

这题可用kmp算法。有串p

next[j] = k,说明 p0pk == pj-k-1pj-1,也就是说k为其前面相等串的长度。所以我们通过字符串最后一个字符的next值就可以得到字符串的重复次数。

package com.woxiaoe.acm.pku.P2406;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {
	
	public static void main(String[] args) {

		//Scanner scn = new Scanner(System.in);
		Scanner scn = new Scanner(Main.class.getResourceAsStream("in.dat"));
		PrintWriter out = new PrintWriter(System.out);
		String input = "";
		List<String> inputs = new ArrayList<String>(5000);
		int index = 0;
		while(scn.hasNext()){
			input = scn.next();
			/*if(input.equals(".")){
				break;
			}*/
			index ++;
			inputs.add(input);
		}
		index --;
		for(int i = 0; i < index; i++ ){
			out.println(kmp(inputs.get(i)));
		}
		out.flush();
	}

	private static int kmp(String input) {
		int len = input.length();
		//char[] pattern = new char[len + 1];
		int[] next = new int[len + 1];
		//System.arraycopy(input.toCharArray(), 0, pattern, 1, len);
		int i = 0,j = -1;
		next[0] = -1;
		while(i < len){
			if( j == -1 || input.charAt(i) == input.charAt(j)){
				i++;
				j++;
				next[i] = j;
			}else{
				j = next[j];
			}
		}
		/*if(len == 2 && pattern[1] == pattern[2]){
			return 2;
		}*/
		if(len % (len - next[len]) == 0){
			return len /(len - next[len]);
		}
		return 1;
	}
}
 

你可能感兴趣的:(java,算法,J#)