📌  相关文章
📜  查找包含另一个字符串所有字符的字符串中的最小窗口

📅  最后修改于: 2021-10-27 07:58:35             🧑  作者: Mango

给定两个字符串,string1 和 string2,任务是高效地找到 string1 中包含 string2 的所有字符的最小子串。

例子:

方法一(暴力破解)
1- 生成 string1 的所有子字符串(“这是一个测试字符串”)
2-对于每个子串,检查子串是否包含string2(“tist”)的所有字符
3- 最后,打印包含 string2 的所有字符的最小子字符串。方法二(高效解决方案)

  1. 首先检查字符串的长度是否小于给定模式的长度,如果是,则“不存在这样的窗口”。
  2. 将给定模式出现的字符存储在 hash_pat[] 中。
  3. 我们将基本上使用两个指针技术
  4. 先从如果一个字符匹配字符串的字符即增量次数匹配模式的字符。
  5. 检查是否 (count == length of pattern ) 这意味着找到了一个窗口。
  6. 如果找到这样的窗口,请尝试通过从当前窗口的开头删除多余的字符来最小化它。
  7. 从第一个字符删除一个字符,然后再次在右侧找到这个已删除的键,一旦找到就应用第 5 步。
  8. 更新 min_length。
  9. 打印最小长度窗口。

解释所述算法的图表:

最小窗口

在第二个图像(数组)之后,我们的左指针应该在 s 然后在右边找到 I 然后应用 step5(基本上没有显示一个步骤)

下面是实现上述算法的程序:

C++
// C++ program to find
// smallest window containing
// all characters of a pattern.
#include 
using namespace std;
 
const int no_of_chars = 256;
 
// Function to find smallest
// window containing
// all characters of 'pat'
string findSubString(string str, string pat)
{
    int len1 = str.length();
    int len2 = pat.length();
 
    // Check if string's length
    // is less than pattern's
    // length. If yes then no such
    // window can exist
    if (len1 < len2) {
        cout << "No such window exists";
        return "";
    }
 
    int hash_pat[no_of_chars] = { 0 };
    int hash_str[no_of_chars] = { 0 };
 
    // Store occurrence ofs characters
    // of pattern
    for (int i = 0; i < len2; i++)
        hash_pat[pat[i]]++;
 
    int start = 0, start_index = -1, min_len = INT_MAX;
 
    // Start traversing the string
    // Count of characters
    int count = 0;
    for (int j = 0; j < len1; j++) {
       
        // Count occurrence of characters
        // of string
        hash_str[str[j]]++;
 
        // If string's char matches with
        // pattern's char
        // then increment count
        if (hash_str[str[j]] <= hash_pat[str[j]])
            count++;
 
        // if all the characters are matched
        if (count == len2) {
           
            // Try to minimize the window
            while (hash_str[str[start]]
                       > hash_pat[str[start]]
                   || hash_pat[str[start]] == 0) {
 
                if (hash_str[str[start]]
                    > hash_pat[str[start]])
                    hash_str[str[start]]--;
                start++;
            }
 
            // update window size
            int len_window = j - start + 1;
            if (min_len > len_window) {
                min_len = len_window;
                start_index = start;
            }
        }
    }
 
    // If no window found
    if (start_index == -1) {
        cout << "No such window exists";
        return "";
    }
 
    // Return substring starting from start_index
    // and length min_len
    return str.substr(start_index, min_len);
}
 
// Driver code
int main()
{
    string str = "this is a test string";
    string pat = "tist";
 
    cout << "Smallest window is : \n"
         << findSubString(str, pat);
    return 0;
}


Java
// Java program to find smallest
// window containing
// all characters of a pattern.
 
public class GFG {
    static final int no_of_chars = 256;
 
    // Function to find smallest
    // window containing
    // all characters of 'pat'
    static String findSubString(String str, String pat)
    {
        int len1 = str.length();
        int len2 = pat.length();
 
        // Check if string's length is
        // less than pattern's
        // length. If yes then no such
        // window can exist
        if (len1 < len2) {
            System.out.println("No such window exists");
            return "";
        }
 
        int hash_pat[] = new int[no_of_chars];
        int hash_str[] = new int[no_of_chars];
 
        // Store occurrence ofs
        // characters of pattern
        for (int i = 0; i < len2; i++)
            hash_pat[pat.charAt(i)]++;
 
        int start = 0, start_index = -1,
            min_len = Integer.MAX_VALUE;
 
        // Start traversing the string
        // Count of characters
        int count = 0;
        for (int j = 0; j < len1; j++) {
           
            // Count occurrence of characters
            // of string
            hash_str[str.charAt(j)]++;
 
            // If string's char matches
            // with pattern's char
            // then increment count
            if (hash_str[str.charAt(j)]
                <= hash_pat[str.charAt(j)])
                count++;
 
            // If all the characters are matched
            if (count == len2) {
               
                // Try to minimize the window
                while (hash_str[str.charAt(start)]
                           > hash_pat[str.charAt(start)]
                       || hash_pat[str.charAt(start)]
                              == 0) {
 
                    if (hash_str[str.charAt(start)]
                        > hash_pat[str.charAt(start)])
                        hash_str[str.charAt(start)]--;
                    start++;
                }
 
                // update window size
                int len_window = j - start + 1;
                if (min_len > len_window) {
                    min_len = len_window;
                    start_index = start;
                }
            }
        }
 
        // If no window found
        if (start_index == -1) {
            System.out.println("No such window exists");
            return "";
        }
 
        // Return substring starting
        // from start_index
        // and length min_len
        return str.substring(start_index,
                             start_index + min_len);
    }
 
    // Driver Method
    public static void main(String[] args)
    {
        String str = "this is a test string";
        String pat = "tist";
 
        System.out.print("Smallest window is :\n "
                         + findSubString(str, pat));
    }
}


Python3
# Python3 program to find the smallest window
# containing all characters of a pattern.
no_of_chars = 256
 
# Function to find smallest window
# containing all characters of 'pat'
def findSubString(string, pat):
 
    len1 = len(string)
    len2 = len(pat)
 
    # Check if string's length is
    # less than pattern's
    # length. If yes then no such
    # window can exist
    if len1 < len2:
 
        print("No such window exists")
        return ""
 
    hash_pat = [0] * no_of_chars
    hash_str = [0] * no_of_chars
 
    # Store occurrence ofs characters of pattern
    for i in range(0, len2):
        hash_pat[ord(pat[i])] += 1
 
    start, start_index, min_len = 0, -1, float('inf')
 
    # Start traversing the string
    count = 0  # count of characters
    for j in range(0, len1):
 
        # count occurrence of characters of string
        hash_str[ord(string[j])] += 1
 
        # If string's char matches with
        # pattern's char then increment count
        if (hash_str[ord(string[j])] <=
                hash_pat[ord(string[j])]):
            count += 1
 
        # if all the characters are matched
        if count == len2:
 
            # Try to minimize the window
            while (hash_str[ord(string[start])] >
                   hash_pat[ord(string[start])] or
                   hash_pat[ord(string[start])] == 0):
 
                if (hash_str[ord(string[start])] >
                        hash_pat[ord(string[start])]):
                    hash_str[ord(string[start])] -= 1
                start += 1
 
            # update window size
            len_window = j - start + 1
            if min_len > len_window:
 
                min_len = len_window
                start_index = start
 
    # If no window found
    if start_index == -1:
        print("No such window exists")
        return ""
 
    # Return substring starting from
    # start_index and length min_len
    return string[start_index: start_index + min_len]
 
 
# Driver code
if __name__ == "__main__":
 
    string = "this is a test string"
    pat = "tist"
 
    print("Smallest window is : ")
    print(findSubString(string, pat))
 
# This code is contributed by Rituraj Jain


C#
// C# program to find smallest
// window containing
// all characters of a pattern.
using System;
 
class GFG {
    static int no_of_chars = 256;
 
    // Function to find smallest
    // window containing
    // all characters of 'pat'
    static String findSubString(String str,
                                String pat)
    {
        int len1 = str.Length;
        int len2 = pat.Length;
 
        // Check if string's length is
        // less than pattern's
        // length. If yes then no such
        // window can exist
        if (len1 < len2) {
            Console.WriteLine("No such window exists");
            return "";
        }
 
        int[] hash_pat = new int[no_of_chars];
        int[] hash_str = new int[no_of_chars];
 
        // Store occurrence ofs characters
        // of pattern
        for (int i = 0; i < len2; i++)
            hash_pat[pat[i]]++;
 
        int start = 0, start_index = -1,
            min_len = int.MaxValue;
 
        // Start traversing the string
        // Count of characters
        int count = 0;
        for (int j = 0; j < len1; j++) {
           
            // Count occurrence of characters
            // of string
            hash_str[str[j]]++;
 
            // If string's char matches
            // with pattern's char
            // then increment count
            if (hash_str[str[j]] <= hash_pat[str[j]])
                count++;
 
            // if all the characters are matched
            if (count == len2) {
               
                // Try to minimize the window
                while (hash_str[str[start]]
                           > hash_pat[str[start]]
                       || hash_pat[str[start]] == 0) {
 
                    if (hash_str[str[start]]
                        > hash_pat[str[start]])
                        hash_str[str[start]]--;
                    start++;
                }
 
                // update window size
                int len_window = j - start + 1;
                if (min_len > len_window) {
                    min_len = len_window;
                    start_index = start;
                }
            }
        }
 
        // If no window found
        if (start_index == -1) {
            Console.WriteLine("No such window exists");
            return "";
        }
 
        // Return substring starting from start_index
        // and length min_len
        return str.Substring(start_index, min_len);
    }
 
    // Driver Method
    public static void Main(String[] args)
    {
        String str = "this is a test string";
        String pat = "tist";
 
        Console.WriteLine("Smallest window is :\n "
                          + findSubString(str, pat));
    }
}
 
/* This code contributed by PrinciRaj1992 */


PHP

                   $hash_pat[ord($str[$start])] ||
                   $hash_pat[ord($str[$start])] == 0)
            {
 
                if ($hash_str[ord($str[$start])] >
                    $hash_pat[ord($str[$start])])
                    $hash_str[ord($str[$start])]--;
                $start++;
            }
 
            // update window size
            $len_window = $j - $start + 1;
            if ($min_len > $len_window)
            {
                $min_len = $len_window;
                $start_index = $start;
            }
        }
    }
 
    // If no window found
    if ($start_index == -1)
    {
        echo "No such window exists";
        return "";
    }
 
    // Return substring starting from
    // start_index and length min_len
    return substr($str, $start_index, $min_len);
}
 
// Driver code
$str = "this is a test string";
$pat = "tist";
 
echo "Smallest window is : \n" .
      findSubString($str, $pat);
       
// This code is contributed by
// rathbhupendra
?>


Javascript


C++14
#include 
using namespace std;
 
// Function
string Minimum_Window(string s, string t)
{
 
    int m[256] = { 0 };
 
    // Answer
    int ans = INT_MAX; // length of ans
    int start = 0; // starting index of ans
    int count = 0;
   
    // creating map
    for (int i = 0; i < t.length(); i++) {
        if (m[t[i]] == 0)
            count++;
        m[t[i]]++;
    }
 
    // References of Window
    int i = 0;
    int j = 0;
 
    // Traversing the window
    while (j < s.length()) {
        // Calculations
        m[s[j]]--;
        if (m[s[j]] == 0)
            count--;
 
        // Condition matching
        if (count == 0) {
            while (count == 0) {
                // Sorting ans
                if (ans > j - i + 1) {
                    ans = min(ans, j - i + 1);
                    start = i;
                }
                // Sliding I
                // Calculation for removing I
 
                m[s[i]]++;
                if (m[s[i]] > 0)
                    count++;
 
                i++;
            }
        }
        j++;
    }
 
    if (ans != INT_MAX)
        return s.substr(start, ans);
    else
        return "-1";
}
 
main()
{
    string s = "ADOBECODEBANC";
    string t = "ABC";
     
      cout<<"-->Smallest window that contain all character : "<


Java
import java.util.*;
 
class GFG{
 
// Function
static String Minimum_Window(char []s, char []t)
{
 
    int m[] = new int[256];
 
    // Answer
    int ans = Integer.MAX_VALUE; // length of ans
    int start = 0; // starting index of ans
    int count = 0;
    // creating map
    for (int i = 0; i < t.length; i++) {
        if (m[t[i]] == 0)
            count++;
        m[t[i]]++;
    }
 
    // References of Window
    int i = 0;
    int j = 0;
 
    // Traversing the window
    while (j < s.length)
    {
       
        // Calculations
        m[s[j]]--;
        if (m[s[j]] == 0)
            count--;
 
        // Condition matching
        if (count == 0)
        {
            while (count == 0)
            {
               
                // Sorting ans
                if (ans > j - i + 1)
                {
                    ans = Math.min(ans, j - i + 1);
                    start = i;
                }
               
                // Sliding I
                // Calculation for removing I
                m[s[i]]++;
                if (m[s[i]] > 0)
                    count++;
 
                i++;
            }
        }
        j++;
    }
 
    if (ans != Integer.MAX_VALUE)
        return String.valueOf(s).substring(start, ans+start);
    else
        return "-1";
}
 
public static void main(String[] args)
{
    String s = "ADOBECODEBANC";
    String t = "ABC";
     
      System.out.print("-->Smallest window that contain all character : ");
    System.out.print(Minimum_Window(s.toCharArray(), t.toCharArray()));
 
}
}
 
// This code is contributed by 29AjayKumar


C#
using System;
 
class GFG{
 
// Function
static String Minimum_Window(char []s, char []t)
{
    int []m = new int[256];
 
    // Answer
    // Length of ans
    int ans = int.MaxValue;
     
    // Starting index of ans
    int start = 0;
    int count = 0, i = 0;
     
    // Creating map
    for(i = 0; i < t.Length; i++)
    {
        if (m[t[i]] == 0)
            count++;
             
        m[t[i]]++;
    }
 
    // References of Window
    i = 0;
    int j = 0;
 
    // Traversing the window
    while (j < s.Length)
    {
         
        // Calculations
        m[s[j]]--;
         
        if (m[s[j]] == 0)
            count--;
 
        // Condition matching
        if (count == 0)
        {
            while (count == 0)
            {
               
                // Sorting ans
                if (ans > j - i + 1)
                {
                    ans = Math.Min(ans, j - i + 1);
                    start = i;
                }
               
                // Sliding I
                // Calculation for removing I
                m[s[i]]++;
                 
                if (m[s[i]] > 0)
                    count++;
 
                i++;
            }
        }
        j++;
    }
 
    if (ans != int.MaxValue)
        return String.Join("", s).Substring(start, ans);
    else
        return "-1";
}
 
// Driver code
public static void Main(String[] args)
{
    String s = "ADOBECODEBANC";
    String t = "ABC";
     
    Console.Write(
        "-->Smallest window that contain all character : ");
    Console.Write(Minimum_Window(s.ToCharArray(),
                                 t.ToCharArray()));
}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出
Smallest window is : 
t stri

方法三(高效解决方案)

(使用滑动窗口技术)

C++14

#include 
using namespace std;
 
// Function
string Minimum_Window(string s, string t)
{
 
    int m[256] = { 0 };
 
    // Answer
    int ans = INT_MAX; // length of ans
    int start = 0; // starting index of ans
    int count = 0;
   
    // creating map
    for (int i = 0; i < t.length(); i++) {
        if (m[t[i]] == 0)
            count++;
        m[t[i]]++;
    }
 
    // References of Window
    int i = 0;
    int j = 0;
 
    // Traversing the window
    while (j < s.length()) {
        // Calculations
        m[s[j]]--;
        if (m[s[j]] == 0)
            count--;
 
        // Condition matching
        if (count == 0) {
            while (count == 0) {
                // Sorting ans
                if (ans > j - i + 1) {
                    ans = min(ans, j - i + 1);
                    start = i;
                }
                // Sliding I
                // Calculation for removing I
 
                m[s[i]]++;
                if (m[s[i]] > 0)
                    count++;
 
                i++;
            }
        }
        j++;
    }
 
    if (ans != INT_MAX)
        return s.substr(start, ans);
    else
        return "-1";
}
 
main()
{
    string s = "ADOBECODEBANC";
    string t = "ABC";
     
      cout<<"-->Smallest window that contain all character : "<

Java

import java.util.*;
 
class GFG{
 
// Function
static String Minimum_Window(char []s, char []t)
{
 
    int m[] = new int[256];
 
    // Answer
    int ans = Integer.MAX_VALUE; // length of ans
    int start = 0; // starting index of ans
    int count = 0;
    // creating map
    for (int i = 0; i < t.length; i++) {
        if (m[t[i]] == 0)
            count++;
        m[t[i]]++;
    }
 
    // References of Window
    int i = 0;
    int j = 0;
 
    // Traversing the window
    while (j < s.length)
    {
       
        // Calculations
        m[s[j]]--;
        if (m[s[j]] == 0)
            count--;
 
        // Condition matching
        if (count == 0)
        {
            while (count == 0)
            {
               
                // Sorting ans
                if (ans > j - i + 1)
                {
                    ans = Math.min(ans, j - i + 1);
                    start = i;
                }
               
                // Sliding I
                // Calculation for removing I
                m[s[i]]++;
                if (m[s[i]] > 0)
                    count++;
 
                i++;
            }
        }
        j++;
    }
 
    if (ans != Integer.MAX_VALUE)
        return String.valueOf(s).substring(start, ans+start);
    else
        return "-1";
}
 
public static void main(String[] args)
{
    String s = "ADOBECODEBANC";
    String t = "ABC";
     
      System.out.print("-->Smallest window that contain all character : ");
    System.out.print(Minimum_Window(s.toCharArray(), t.toCharArray()));
 
}
}
 
// This code is contributed by 29AjayKumar

C#

using System;
 
class GFG{
 
// Function
static String Minimum_Window(char []s, char []t)
{
    int []m = new int[256];
 
    // Answer
    // Length of ans
    int ans = int.MaxValue;
     
    // Starting index of ans
    int start = 0;
    int count = 0, i = 0;
     
    // Creating map
    for(i = 0; i < t.Length; i++)
    {
        if (m[t[i]] == 0)
            count++;
             
        m[t[i]]++;
    }
 
    // References of Window
    i = 0;
    int j = 0;
 
    // Traversing the window
    while (j < s.Length)
    {
         
        // Calculations
        m[s[j]]--;
         
        if (m[s[j]] == 0)
            count--;
 
        // Condition matching
        if (count == 0)
        {
            while (count == 0)
            {
               
                // Sorting ans
                if (ans > j - i + 1)
                {
                    ans = Math.Min(ans, j - i + 1);
                    start = i;
                }
               
                // Sliding I
                // Calculation for removing I
                m[s[i]]++;
                 
                if (m[s[i]] > 0)
                    count++;
 
                i++;
            }
        }
        j++;
    }
 
    if (ans != int.MaxValue)
        return String.Join("", s).Substring(start, ans);
    else
        return "-1";
}
 
// Driver code
public static void Main(String[] args)
{
    String s = "ADOBECODEBANC";
    String t = "ABC";
     
    Console.Write(
        "-->Smallest window that contain all character : ");
    Console.Write(Minimum_Window(s.ToCharArray(),
                                 t.ToCharArray()));
}
}
 
// This code is contributed by 29AjayKumar

Javascript


输出:

-->Smallest window that contain all character : 
BANC

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程