ACM HDOJ 1867 (A + B for you again)
2014-01-19 21:54
357 查看
题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=1867
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 kmp1 = new Kmp(str1.toCharArray(), str2.toCharArray()); Kmp kmp2 = new Kmp(str2.toCharArray(), str1.toCharArray()); int position1 = kmp1.match(); int position2 = kmp2.match(); if (position1 == position2) { if (0 > str1.compareTo(str2)) { System.out.print(str1); System.out.println(str2.substring(position1)); } else { System.out.print(str2); System.out.println(str1.substring(position2)); } } else if (position1 > position2) { System.out.print(str1); System.out.println(str2.substring(position1)); } else { System.out.print(str2); System.out.println(str1.substring(position2)); } } 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 int match() { calculateNext(); int i = 0, j = 0; while (i < modelLength && j < patternLength) { if (-1 == j || model[i] == pattern[j]) { ++i; ++j; } else { j = next[j]; } } if (i < modelLength) { j = 0; } return j; } }
相关文章推荐
- 【HDOJ】1867 A + B for you again
- HDOJ 题目1867A + B for you again(KMP)
- hdoj 1867 A + B for you again【kmp,前缀与后缀的匹配】
- hdu 1867 A + B for you again KMP
- HDU 1867 A + B for you again(KMP算法的应用)
- 【KMP】hdu 1867 A + B for you again(外:hdu 2594 Simpsons’ Hidden Talents)
- KMP——HDU 1867 A + B for you again
- HDU 1867 A + B for you again (KMP)
- HDU 1867 A + B for you again 字符串拼接 kmp
- 杭电1867 A + B for you again
- HDU 1867 A + B for you again (KMP应用)
- KMP——HDU 1867 A + B for you again
- HDU 1867 A + B for you again——kmp
- HDU 1867:A + B for you again
- hdu 1867 A + B for you again
- hdu 1867 A + B for you again(KMP)
- HDU(1867)A + B for you again (KMP)
- KMP——HDU 1867 A + B for you again
- hdu 1867 A + B for you again (kmp)
- Hdu-1867 A + B for you again