算法竞赛入门-子序列(All in All)

1.题目

You have devised a new encryption technique which encodes a message by inserting between its characters randomly generated strings in a clever way. Because of pending patent issues we will not discuss in detail how the strings are generated and inserted into

the original message. To validate your method, however, it is necessary to write a program that checks if the message is really encoded in the final string. 
Given two strings s and t, you have to decide whether s is a subsequence of t, i.e. if you can remove characters from t such that the concatenation of the remaining characters is s. 
Input

The input contains several testcases. Each is specified by two strings s, t of alphanumeric ASCII characters separated by whitespace.The length of s and t will no more than 100000.

Output

For each test case output “Yes”, if s is a subsequence of t,otherwise output “No”.

Sample Input

sequence subsequence
person compression
VERDI vivaVittorioEmanueleReDiItalia
caseDoesMatter CaseDoesMatter
  • 1
  • 2
  • 3
  • 4

Sample Output

Yes
No
Yes
No

2.思路

遍历字符串,获取下标,判断下标时候为顺序增长即可。

3.代码

package basic.第三章;

import java.util.Arrays;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 子序列(All in All)
 * Created by Administrator on 2018/4/12.
 *
 * @author  春风吹又生
 */
public class AllInAll {
    public static void main(String[] args) {
        Scanner read = new Scanner(System.in);
        String[] str = read.nextLine().split(" ");
        String s = str[0];
        String t = str[1];
        char[] chs = s.toCharArray();
        String tmp = t;
        int[] arr = new int[chs.length];
        for (int i = 0; i < chs.length; i++) {
            arr[i] = -1;
        }
        for (int i = 0; i < chs.length; i++) {
            Pattern pattern = Pattern.compile(chs[i] + "");
            Matcher matcher = pattern.matcher(t);
            while (matcher.find()) {  //查找符合规则的子串
                if (i == 0) {
                    arr[i] = matcher.start() == 0 ? 0 : arr[i] == -1 ? matcher.start() : matcher.start() < arr[i] ? matcher.start() : arr[i];
                } else if (matcher.start() < arr[i - 1]) {
                    continue;
                } else {
                    arr[i] = arr[i] == -1 ? matcher.start() : matcher.start() < arr[i] ? matcher.start() : arr[i];
                }
            }
        }
        int length = arr.length;
        boolean flag = true;
        for (int i = 0; i < length - 1; i++) {
            if (arr[i] == -1) flag = false;
            if (arr[i] > arr[i + 1]) {
                flag = false;
                break;
            }
        }
        if (flag) {
            System.out.println("yes");
        } else
            System.out.println("no");

    }
}

你可能感兴趣的:(Java,算法,算法竞赛入门)