面试题之子串匹配

又到了面试季,最近问了一个问题,好像不太好答,于是自己试试

package test20190925.test20190925;

import java.util.Arrays;

public class SubStringCheck {

    public static String sortStringChar(String s) {
        char[] chars = s.toCharArray();
        Arrays.sort(chars);
        return new String(chars);
    }
    
    public static boolean checkContains(String s1, String s2) {
        String s1Sorted = sortStringChar(s1);
        //System.out.println(s1Sorted);
        int s1Length = s1Sorted.length();
        int s2Length = s2.length();
        for (int i = 0; i <= s2Length - s1Length; i++) {
            String s2Capture = s2.substring(i, i + s1Length);
            //System.out.println(s2Capture);
            String s2CaptureSorted = sortStringChar(s2Capture);
            if (s1Sorted.equals(s2CaptureSorted)) {
                return true;
            }
        }
        return false;
    }
    
    public static void main(String[] args) {
        System.out.println(checkContains("abc", "eidboaoo"));
    }

}

Leave a Reply

Your email address will not be published. Required fields are marked *