Quantcast
Channel: ZRJ
Viewing all articles
Browse latest Browse all 120

面试题之子串匹配

$
0
0

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

leetcode 567 https://leetcode.com/problems/…

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"));
    }

}

2021-9-30 又搞了一个 c++ 的,这个快很多,内存也小

class Solution {
public:
    bool checkInclusion(string s1, string s2) {        
        vector<int> s1count(26), s2count(26);
        for (size_t i = 0; i < s1.length() && i < s2.length(); i++) {
            s1count[s1.at(i) - 'a']++;
            s2count[s2.at(i) - 'a']++;
        }
        for (size_t i = s1.length() - 1; i < s2.length(); i++) {
            if (s1count == s2count) {
                return true;
            }
            if (i + 1 < s2.length()) {
                s2count[s2.at(i - s1.length() + 1) - 'a']--;
                s2count[s2.at(i + 1) - 'a']++;
            }
        }
        return false;
    }
    
};

Viewing all articles
Browse latest Browse all 120

Trending Articles


Girasoles para colorear


mayabang Quotes, Torpe Quotes, tanga Quotes


Tagalog Quotes About Crush – Tagalog Love Quotes


OFW quotes : Pinoy Tagalog Quotes


Long Distance Relationship Tagalog Love Quotes


Tagalog Quotes To Move on and More Love Love Love Quotes


5 Tagalog Relationship Rules


Best Crush Tagalog Quotes And Sayings 2017


Re:Mutton Pies (lleechef)


FORECLOSURE OF REAL ESTATE MORTGAGE


Sapos para colorear


tagalog love Quotes – Tiwala Quotes


Break up Quotes Tagalog Love Quote – Broken Hearted Quotes Tagalog


Patama Quotes : Tagalog Inspirational Quotes


Pamatay na Banat and Mga Patama Love Quotes


Tagalog Long Distance Relationship Love Quotes


BARKADA TAGALOG QUOTES


“BAHAY KUBO HUGOT”


Vimeo 10.7.0 by Vimeo.com, Inc.


Vimeo 10.7.1 by Vimeo.com, Inc.