Substring Search

Generalization: substring search problem Template:

class Solution {

public:
    T minWindow(string s, string t) {
        if(t.length() > s.length()) return "";
        unordered_map <char, int> map;
        for(int i = 0; i < t.length(); i++ ){
            ++map[t[i]];
        }

        int left = 0, right = 0, head = INT_MAX, len = INT_MAX, count = map.size();

        while(right < s.length()){
            char rightChar = s[right];
            if(map.find(rightChar) != map.end()){
                if(--map[rightChar] == 0) count --; // here condition statement and -- or ++ depending on cases 
            }
            right ++;
            while(count == 0){     // here condition statement depends on cases
                // do 

                // increment
                char leftChar = s[left];
                if (map.find(leftChar)!= map.end()){
                    if(++map[leftChar] > 0){
                        count++;
                    }
                }       
                left ++;
            }
        }


        return T; //<answer to return>;
    }
};

Original Java Code from the LeetCode Forum harrychaoyanghearrow-up-right

C++ Template: https://leetcode.com/problems/minimum-window-substring/discuss/26808/Here-is-a-10-line-template-that-can-solve-most-'substring'-problemsarrow-up-right

Longest Substring with At Most Two Distinct Characters, Longest Substring with At Most K Distinct Characters, Minimum Window Substring, Longest Substring Without Repeating Characters

Minimum Window Substring

Longest Substring with At Most Two Distinct Characters:

Longest Substring Without Repeating Characters

Special thanks: LeetCode Discussion Forumarrow-up-right for the reference!

Last updated

Was this helpful?