述 |
题目标题: 判断短字符串中的所有字符是否在长字符串中全部出现 详细描述: 接口说明 原型: boolIsAllCharExist(char* pShortString,char* pLongString); 输入参数: char* pShortString:短字符串 char* pLongString:长字符串
|
---|---|
知识点 |
字符串,循环,指针 |
运行时间限制 |
10M |
内存限制 |
128 |
输入 |
输入两个字符串。第一个为短字符,第二个为长字符。 |
输出 |
返回值: true - 表示短字符串中所有字符均在长字符串中出现 false- 表示短字符串中有字符在长字符串中没有出现
|
样例输入 |
bc abc |
样例输出 |
true |
题目坑点:不需要连续
(KMP匹配算法或者HashSet)
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
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;
}
}
KMP算法:
对于朴素匹配算法的改进是引入了一个跳转表next[]。
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;
}
}
若要求连续,s2包含s1字符串
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String minS = scanner.next();
String maxS = scanner.next();
System.out.print(match(minS,maxS));
}
scanner.close();
}
private static boolean match(String s1,String s2){
char[] ch1=s1.toCharArray();
char[] ch2=s2.toCharArray();
int start=0;int end=0;
for(int i=0;i<ch2.length;i++){
if(ch2[i]==ch1[0]){
start=i;
}
if(ch2[i]==ch1[ch1.length-1]){
end=i;
}
}
String ss2=s2.substring(start,end+1);
if(s1.equals(ss2)){
return true;
}
return false;
}
}