华为OD机考-字符串子序列II-字符串(JAVA 2025B卷)

华为OD机考-字符串子序列II-字符串(JAVA 2025B卷)_第1张图片
华为OD机考-字符串子序列II-字符串(JAVA 2025B卷)_第2张图片

import java.util.Scanner;

public class SubSequenceLastIndex {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String target = sc.nextLine();
            String source = sc.nextLine();
            int targetLen = target.length();
            int sourceLen = source.length();
            int i = targetLen - 1;
            int j = sourceLen - 1;
            // 标识是否有匹配的子序列
            boolean flag = false;
            // 逆序遍历
            while (i >= 0 && j >= 0) {
                if (target.charAt(i) == source.charAt(j)) {
                    if (i == 0) {
                        // 指针走到target第0位,说明能够匹配完目标字符串
                        flag = true;
                        System.out.println(j);
                    }
                    i--;
                    j--;
                } else {
                    // 没有找到相等的字符,继续向左遍历source字符串
                    j--;
                }
            }
            if (!flag) {
                System.out.println(-1);
            }
        }
        sc.close();
    }
}


你可能感兴趣的:(华为机考,java,华为od,开发语言)