热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

在包含另一个字符串的所有字符的字符串中找到最小的窗口

在包含另一个字符串的所有字符的字符串中找到最小的窗口原文:htt

在包含另一个字符串的所有字符的字符串中找到最小的窗口

原文:https://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-containing-all-characters-of-another-string/

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

示例

输入string = "this is a test string", pattern = "tist"

输出:最小窗口为"t stri"

说明"t stri"包含模式的所有字符。

输入string = "geeksforgeeks", pattern = "ork"

输出:最小窗口为"ksfor"

方法 1(暴力解)


  1. 生成string1的所有子字符串("this is a test string


  2. 对于每个子字符串,检查子字符串是否包含string2的所有字符("tist)。


  3. 最后,打印包含string2所有字符的最小子字符串。


方法 2(有效解决方案)


  1. 首先检查字符串的长度是否小于给定模式的长度,如果是,则"no such window can exist"


  2. 将给定模式的字符的出现存储在hash_pat[]中。


  3. 开始将pattern的字符与字符串的字符进行匹配,即如果一个字符匹配,则增加计数。


  4. 检查计数是否等于模式长度,表示找到了一个窗口。


  5. 如果找到了这样的窗口,请尝试通过从当前窗口的开头删除多余的字符来最小化它。


  6. 更新min_length


  7. 打印最小长度窗口。


解释上述算法的图

smallest-window

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

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     {
        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         hash_pat[pat[i]]++;
    int start = 0, start_index = -1, min_len = INT_MAX;
    // start traversing the string
    int count = 0; // count of characters
    for (int j = 0; 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_pat[str[j]] != 0 &&
            hash_str[str[j]] <= hash_pat[str[j]] )
            count++;
        // if all the characters are matched
        if (count == len2)
        {
            // Try to minimize the window i.e., check if
            // any character is occurring more no. of times
            // than its occurrence in pattern, if yes
            // then remove it from starting and also remove
            // the useless characters.
            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"
        <    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         {
            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             hash_pat[pat.charAt(i)]++;
        int start = 0, start_index = -1, min_len = Integer.MAX_VALUE;
        // start traversing the string
        int count = 0; // count of characters
        for (int j = 0; 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_pat[str.charAt(j)] != 0 &&
                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 i.e., check if
                // any character is occurring more no. of times
                // than its occurrence in pattern, if yes
                // then remove it from starting and also remove
                // the useless characters.
                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         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_pat[ord(string[j])] != 0 and
            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 i.e., check if 
            # any character is occurring more no. of times 
            # than its occurrence in pattern, if yes 
            # then remove it from starting and also remove 
            # the useless characters. 
            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         {
            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             hash_pat[pat[i]]++;
        int start = 0, start_index = -1, min_len = int.MaxValue;
        // start traversing the string
        int count = 0; // count of characters
        for (int j = 0; 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_pat[str[j]] != 0 &&
                hash_str[str[j]] <= hash_pat[str[j]] )
                count++;
            // if all the characters are matched
            if (count == len2)
            {
                // Try to minimize the window i.e., check if
                // any character is occurring more no. of times
                // than its occurrence in pattern, if yes
                // then remove it from starting and also remove
                // the useless characters.
                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

// PHP program to find smallest window 
// containing all characters of a pattern. 
define("no_of_chars", 256); 
// Function to find smallest window 
// containing all characters of 'pat' 
function findSubString(&$str, &$pat) 

    $len1 = strlen($str); 
    $len2 = strlen($pat); 
    // check if string's length is less 
    // than pattern's length. If yes
    // then no such window can exist 
    if ($len1 <$len2) 
    { 
        echo "No such window exists"; 
        return ""; 
    } 
    $hash_pat = array_fill(0, no_of_chars, 0); 
    $hash_str = array_fill(0, no_of_chars, 0); 
    // store occurrence ofs characters
    // of pattern 
    for ($i = 0; $i <$len2; $i++) 
        $hash_pat[ord($pat[$i])]++; 
    $start = 0;
    $start_index = -1;
    $min_len = PHP_INT_MAX; 
    // start traversing the string 
    $count = 0; // count of characters 
    for ($j = 0; $j <$len1 ; $j++) 
    { 
        // count occurrence of characters
        // of string 
        $hash_str[ord($str[$j])]++; 
        // If string's char matches with 
        // pattern's char then increment count 
        if ($hash_pat[ord($str[$j])] != 0 && 
            $hash_str[ord($str[$j])] <=
            $hash_pat[ord($str[$j])]) 
            $count++; 
        // if all the characters are matched 
        if ($count == $len2) 
        { 
            // Try to minimize the window i.e., 
            // check if any character is occurring 
            // more no. of times than its occurrence 
            // in pattern, if yes then remove it from
            // starting and also remove the useless 
            // characters. 
            while ($hash_str[ord($str[$start])] > 
                   $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
?>

输出

Smallest window is :
t stri

本文由 Sahil Chhabra 提供。 如果您喜欢 GeeksforGeeks 并希望做出贡献,则也可以使用 contribution.geeksforgeeks.org 撰写文章,或将您的文章邮寄到 contribution@geeksforgeeks.org。 查看您的文章出现在 GeeksforGeeks 主页上,并帮助其他 Geeks。

如果发现任何不正确的地方,或者想分享有关上述主题的更多信息,请写评论。


推荐阅读
  • 开发笔记:Java是如何读取和写入浏览器Cookies的
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了Java是如何读取和写入浏览器Cookies的相关的知识,希望对你有一定的参考价值。首先我 ... [详细]
  • 本文介绍了Java中Hashtable的clear()方法,该方法用于清除和移除指定Hashtable中的所有键。通过示例程序演示了clear()方法的使用。 ... [详细]
  • 微软头条实习生分享深度学习自学指南
    本文介绍了一位微软头条实习生自学深度学习的经验分享,包括学习资源推荐、重要基础知识的学习要点等。作者强调了学好Python和数学基础的重要性,并提供了一些建议。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
  • [大整数乘法] java代码实现
    本文介绍了使用java代码实现大整数乘法的过程,同时也涉及到大整数加法和大整数减法的计算方法。通过分治算法来提高计算效率,并对算法的时间复杂度进行了研究。详细代码实现请参考文章链接。 ... [详细]
  • JDK源码学习之HashTable(附带面试题)的学习笔记
    本文介绍了JDK源码学习之HashTable(附带面试题)的学习笔记,包括HashTable的定义、数据类型、与HashMap的关系和区别。文章提供了干货,并附带了其他相关主题的学习笔记。 ... [详细]
  • Java程序设计第4周学习总结及注释应用的开发笔记
    本文由编程笔记#小编为大家整理,主要介绍了201521123087《Java程序设计》第4周学习总结相关的知识,包括注释的应用和使用类的注释与方法的注释进行注释的方法,并在Eclipse中查看。摘要内容大约为150字,提供了一定的参考价值。 ... [详细]
  • 本文介绍了一个适用于PHP应用快速接入TRX和TRC20数字资产的开发包,该开发包支持使用自有Tron区块链节点的应用场景,也支持基于Tron官方公共API服务的轻量级部署场景。提供的功能包括生成地址、验证地址、查询余额、交易转账、查询最新区块和查询交易信息等。详细信息可参考tron-php的Github地址:https://github.com/Fenguoz/tron-php。 ... [详细]
  • 本文讨论了在VMWARE5.1的虚拟服务器Windows Server 2008R2上安装oracle 10g客户端时出现的问题,并提供了解决方法。错误日志显示了异常访问违例,通过分析日志中的问题帧,找到了解决问题的线索。文章详细介绍了解决方法,帮助读者顺利安装oracle 10g客户端。 ... [详细]
  • Java 11相对于Java 8,OptaPlanner性能提升有多大?
    本文通过基准测试比较了Java 11和Java 8对OptaPlanner的性能提升。测试结果表明,在相同的硬件环境下,Java 11相对于Java 8在垃圾回收方面表现更好,从而提升了OptaPlanner的性能。 ... [详细]
author-avatar
用巛户khm8pcnjp9
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有