【最多提取子串数目 | 挑选字符串】
给定a-z,26个英文字母小写字符串组成的字符串A和B,
其中A可能存在重复字母,B不会存在重复字母,
现从字符串A中按规则挑选一些字母可以组成字符串B。
挑选规则如下:
同一个位置的字母只能挑选一次,
被挑选字母的相对先后顺序不能被改变,
求最多可以同时从A中挑选多少组能组成B的字符串。
输入描述
输入为2行,第一行输入字符串a,第二行输入字符串b,行首行尾没有多余空格
输出描述
输出一行,包含一个数字,表示最多可以同时从a中挑选多少组能组成b的字符串,行未没有多余空格
用例1
输入
badc
bac
输出
1
import java.util.*;
public class OdAb22 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String a = scanner.nextLine(); // 读取字符串a
String b = scanner.nextLine(); // 读取字符串b
int result = getResult(a, b); // 获取最多可以同时从a中选择多少组能组成b的字符串
System.out.println(result); // 输出结果
}
private static int getResult(String a, String b) {
Map<Character, Integer> idxMap = new HashMap<>(); // 记录字符串b中每个字符的索引
for (int i = 0; i < b.length(); i++) {
idxMap.put(b.charAt(i), i);
}
// 用于记录符合顺序要求的字符串b中每个字符出现的次数
List<Integer> count = new ArrayList<>(Collections.nCopies(b.length(), 0));
for (char c : a.toCharArray()) { // 遍历a中的每个字符
Integer idx = idxMap.get(c);
if (idx != null && (idx == 0 || count.get(idx) < count.get(idx - 1))) {
// 如果c字符在b中存在且满足顺序要求,则将其出现的次数加1
count.set(idx, count.get(idx) + 1);
}
}
return count.get(b.length() - 1); // 返回符合顺序要求的字符串b中最后一个字符出现的次数
}
}