1. 利用正则表达式取巧
public class Main
{
static Set<String> set = new HashSet<String>(); // 存放B可能代表的字符串
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
// 从输入流中读数据
String strA = sc.nextLine().trim();
String strB = sc.nextLine().trim();
// 如果字符串strB比strA更长
if (strB.length() > strA.length())
{
System.out.println(0);
return;
}
// 将所有的?替换成.
strB = strB.replace('?', '.');
// 编译正则表达式
Pattern p = Pattern.compile(strB);
// 使用pattern对strA进行匹配
Matcher m = p.matcher(strA);
int startIndex = 0; // 搜索的起始下标
int endIndex = strA.length(); // 要搜索的字符串的长度
while (startIndex < endIndex && m.find(startIndex))
{
set.add(m.group(0)); // 将匹配到的整个串中的内容放到set中
startIndex++;
}
// 打印匹配的字符串的种数
System.out.println(set.size());
}
}
2. 常规思路(KMP)
public class Main
{
static Set<String> set = new HashSet<String>(); // 存放B可能代表的字符串
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
// 得到字符串A和B
String strA = scan.nextLine().trim();
String strB = scan.nextLine().trim();
// 计算字符串A和B的长度
int lenA = strA.length();
int lenB = strB.length();
// 如果字符串strB比strA更长
if (lenB > lenA)
{
System.out.println(0);
return;
}
int scope = lenA-lenB+1;// 有效搜索范围
String subStr = null; // 子串
boolean flag = true;
for (int i=0; i<scope; i++)
{
subStr = strA.substring(i, i+lenB);
flag = true;
// 逐个检查字符是否匹配
for (int j=0; j<lenB; j++)
{
if (strB.charAt(j) == '?')
continue;
if (subStr.charAt(j) != strB.charAt(j))
{
flag = false; // 表示不匹配
break;
}
}
if (flag == true)
set.add(subStr);
}
// 输出匹配的字符串种数
System.out.println(set.size());
}
}