【华为OJ】【算法总篇章】
【华为OJ】【055-字符串匹配】
【工程下载】
题目描述
题目标题:
判断短字符串中的所有字符是否在长字符串中全部出现
输入描述:
输入两个字符串。第一个为短字符,第二个为长字符。
输出描述:
返回值:true或者false
输入例子:
bc
abc
输出例子:
true
算法实现
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
/**
* Author: 王俊超
* Date: 2015-12-25 13:53
* All Rights Reserved !!!
*/
public class Main {
public static void main(String[] args) {
// Scanner scanner = new Scanner(System.in);
Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
while (scanner.hasNext()) {
String sub = scanner.next();
String s = scanner.next();
System.out.println(contains(s, sub));
}
scanner.close();
}
private static boolean contains(String s, String sub) {
Set<Character> set = new HashSet<>();
for (int i = 0; i < s.length(); i++) {
set.add(s.charAt(i));
}
for (int i = 0; i < sub.length(); i++) {
if (!set.contains(sub.charAt(i))) {
return false;
}
}
return true;
}
}
/**
* Author: 王俊超
* Date: 2015-12-25 15:08
* All Rights Reserved !!!
*/
public class KMP {
// 下面的KMP匹配算法,于
private static boolean kmpMatch( String s, String sub) {
int[] next = getNext(sub);
// 母串的长度
int m = s.length();
// 子串的长度
int n = sub.length();
int j = 0;
int i = -1;
for(; j < m; j++) {
while (sub.charAt(i + 1) != s.charAt(j) && i >= 0) {
i = next[i];
}
if (sub.charAt(i + 1) == s.charAt(j)) {
i++;
}
if (i == n - 1) {
return true;
}
}
return false;
}
private static int[] getNext(String s) {
// next[j] 表示当 W[j] 与 S[i] 不匹配时,W 应该滑到哪个位置上。
int[] next = new int[s.length()];
next[0] = -1;
next[1] = 0;
// j在前
int i = 0;
int j = -1;
while (i < s.length() - 1) {
if (j == -1 || s.charAt(i) == s.charAt(j)) {
if (s.charAt(++i) != s.charAt(++j)) {
next[i] = j;
} else {
// 回退
next[i] = next[j];
}
} else {
// 回退
j = next[j];
}
}
return next;
}
}