ACM HDOJ 2203 (亲和串)

12 篇文章 0 订阅
4 篇文章 0 订阅

题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=2203

程序一 KMP 算法 允许变量i回溯一次

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner scn = new Scanner(System.in);
		while (scn.hasNext()) {
			String str1 = scn.next();
			String str2 = scn.next();
			Kmp kmp = new Kmp(str1.toCharArray(), str2.toCharArray());
			if (kmp.match()) {
				System.out.println("yes");
			} else {
				System.out.println("no");
			}
		}
		scn.close();
	}

}

class Kmp {

	private int modelLength;
	private int patternLength;
	private char[] model;
	private char[] pattern;
	private int[] next;

	private void calculateNext() {
		int i = 0, j = -1;
		next[0] = -1;
		while (i < patternLength - 1) {
			if (-1 == j || pattern[i] == pattern[j]) {
				++i;
				++j;
				if (pattern[i] != pattern[j]) {
					next[i] = j;
				} else {
					next[i] = next[j];
				}
			} else {
				j = next[j];
			}
		}
	}

	public Kmp(char[] model, char[] pattern) {
		modelLength = model.length;
		patternLength = pattern.length;
		this.model = model;
		this.pattern = pattern;
		next = new int[patternLength];
	}

	public boolean match() {
		calculateNext();
		int i = 0, j = 0, circle = 0;
		while (i < modelLength && j < patternLength && 1 >= circle) {
			if (-1 == j || model[i] == pattern[j]) {
				++i;
				++j;
				if (i == modelLength) {
					++circle;
					i = 0; // 允许i回溯一次
				}
			} else {
				j = next[j];
			}
		}
		if (j == patternLength) {
			return true;
		} else {
			return false;
		}
	}

}

程序二 String类的indexOf方法

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner scn = new Scanner(System.in);
		while (scn.hasNext()) {
			String str1 = scn.next();
			String str2 = scn.next();
			str1 += str1;
			if (0 <= str1.indexOf(str2)) {
				System.out.println("yes");
			} else {
				System.out.println("no");
			}
		}
		scn.close();
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值