华为OD 关联子串

题目描述

给定两个字符串str1和str2,如果字符串str1中的字符,经过排列组合后的字符串中,只要有一个字符串是str2的子串,则认为str1是str2的关联子串。

若str1是str2的关联子串,请返回子串在str2的起始位置;

若不是关联子串,则返回-1。

输入描述

输入两个字符串,分别为题目中描述的str1、str2。

输出描述

若str1是str2的关联子串,请返回子串在str2的起始位置;

若不是关联子串,则返回-1。

若str2中有多个str1的组合子串,请返回最小的起始位置。

备注

  • 输入的字符串只包含小写字母;
  • 两个字符串的长度范围[1, 100000]之间;

用例1

输入

abc efghicbaiii

输出

5

说明

str2包含str1的一种排列组合("cab"),此组合在str2的字符串起始位置为5(从0开始计数)

用例2

输入

abc efghiccaiii

输出

-1

说明

“abc”字符串中三个字母的各种组合(abc、acb、bac、bca、cab、cba),str2中均不包含,因此返回-1

import java.util.Scanner;
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String[] strs = in.nextLine().split(" ");
        String str1 = strs[0];
        String str2 = strs[1];
        char[] chars = strs[0].toCharArray();
        List<Character> list = new ArrayList<Character>();
        for (char ch : chars) {
            list.add(ch);
        }
        int index = 0;
        List<Character> dealList = new ArrayList<Character>(Arrays.asList(new Character[list.size()]));
        Collections.copy(dealList, list);
        Boolean tag = true;
        for (int i = 0; i < str2.length(); i++) {
            if (list.contains(str2.charAt(i))) {
                boolean removed = dealList.remove((Character)str2.charAt(i));
                if(removed &&  dealList.size() == 0){
                    System.out.println(index);
                    return ;
                }
                if(!removed){
                    dealList = getListCopy(list);
                    dealList.remove((Character)str2.charAt(i));
                    index = i;
                }
                if (tag) {
                    index = i;
                }
                tag = false;
            } else {
                if (dealList.size() == 0) {
                    System.out.println(index);
                    return ;
                } else if (dealList.size() != list.size() && dealList.size() != 0) {
                    dealList = getListCopy(list);
                    tag = true;                
               }
                
            }
        }
        System.out.println("-1");
    }

    public static List<Character> getListCopy(List<Character> list){
         List<Character> dealList = new ArrayList<Character>(Arrays.asList(new Character[list.size()]));
        Collections.copy(dealList, list);
        return dealList;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值