📌  相关文章
📜  检查字符串是否遵循模式定义的字符顺序 |设置 2

📅  最后修改于: 2022-05-13 01:57:08.665000             🧑  作者: Mango

检查字符串是否遵循模式定义的字符顺序 |设置 2

给定一个输入字符串和一个模式,检查输入字符中的字符串是否遵循与模式中存在的字符相同的顺序。假设模式中不会有任何重复的字符。
同一问题的另一种解决方案在此处发布。
例子:

Input: string = "engineers rock", pattern = "er";
Output: true
All 'e' in the input string are before all 'r'.

Input: string = "engineers rock", pattern = "egr";
Output: false
There are two 'e' after 'g' in the input string.

Input: string = "engineers rock", pattern = "gsr";
Output: false
There are one 'r' before 's' in the input string.

这里的想法是将给定的字符串减少到给定的模式。对于模式中给定的字符,我们只保留字符串中的对应字符。在新字符串中,我们删除连续重复的字符。修改后的字符串应该等于给定的模式。最后,我们将修改后的字符串与给定的模式进行比较,并相应地返回 true 或 false。
插图:

str = "bfbaeadeacc", pat[] = "bac"

1) Remove extra characters from str (characters
  that are not present in pat[]
str = "bbaaacc"   [f, e and d are removed]

3) Removed consecutive repeating occurrences of 
   characters
str = "bac"   

4) Since str is same as pat[], we return true

下面是上述步骤的实现。

Java
// Java program to check if characters of a string follow
// pattern defined by given pattern.
import java.util.*;
 
public class OrderOfCharactersForPattern
{
    public static boolean followsPattern(String str, String pattern)
    {
        // Insert all characters of pattern in a hash set,
        Set patternSet = neHashSet<>();
        for (int i=0; i=0; i--)
            if (!patternSet.contains(modifiedString.charAt(i)))
                modifiedString.deleteCharAt(i);
 
        // Remove more than one consecutive occurrences of pattern
        // characters from modified string.
        for (int i=modifiedString.length()-1; i>0; i--)
            if (modifiedString.charAt(i) == modifiedString.charAt(i-1))
                modifiedString.deleteCharAt(i);
 
        // After above modifications, the length of modified string
        // must be same as pattern length
        if (pattern.length() != modifiedString.length())
            return false;
 
        // And pattern characters must also be same as modified string
        // characters
        for (int i=0; i


Python3
# Python3 program to check if characters of
# a string follow pattern defined by given pattern.
def followsPattern(string, pattern):
 
    # Insert all characters of pattern in a hash set,
    patternSet = set()
 
    for i in range(len(pattern)):
        patternSet.add(pattern[i])
 
    # Build modified string (string with characters
    # only from pattern are taken)
    modifiedString = string
    for i in range(len(string) - 1, -1, -1):
        if not modifiedString[i] in patternSet:
            modifiedString = modifiedString[:i] + \
                             modifiedString[i + 1:]
 
    # Remove more than one consecutive occurrences
    # of pattern characters from modified string.
    for i in range(len(modifiedString) - 1, 0, -1):
        if modifiedString[i] == modifiedString[i - 1]:
            modifiedString = modifiedString[:i] + \
                             modifiedString[i + 1:]
 
    # After above modifications, the length of
    # modified string must be same as pattern length
    if len(pattern) != len(modifiedString):
        return False
 
    # And pattern characters must also be same
    # as modified string characters
    for i in range(len(pattern)):
        if pattern[i] != modifiedString[i]:
            return False
    return True
 
# Driver Code
if __name__ == "__main__":
    string = "engineers rock"
    pattern = "er"
    print("Expected: true, Actual:",
           followsPattern(string, pattern))
 
    string = "engineers rock"
    pattern = "egr"
    print("Expected: false, Actual:",
           followsPattern(string, pattern))
 
    string = "engineers rock"
    pattern = "gsr"
    print("Expected: false, Actual:",
           followsPattern(string, pattern))
 
    string = "engineers rock"
    pattern = "eger"
    print("Expected: true, Actual:",
           followsPattern(string, pattern))
 
# This code is contributed by
# sanjeev2552


C#
// C# program to check if characters of a string follow
// pattern defined by given pattern.
using System;
using System.Collections.Generic;
using System.Text;
 
class GFG
{
    public static bool followsPattern(String str, String pattern)
    {
        // Insert all characters of pattern in a hash set,
        HashSet patternSet = new HashSet();
        for (int i = 0; i < pattern.Length; i++)
            patternSet.Add(pattern[i]);
 
        // Build modified string (string with characters
        // only from pattern are taken)
        StringBuilder modifiedString = new StringBuilder(str);
        for (int i = str.Length - 1; i >= 0; i--)
            if (!patternSet.Contains(modifiedString[i]))
                modifiedString.Remove(i, 1);
 
        // Remove more than one consecutive occurrences of pattern
        // characters from modified string.
        for (int i = modifiedString.Length - 1; i > 0; i--)
            if (modifiedString[i] == modifiedString[i - 1])
                modifiedString.Remove(i, 1);
 
        // After above modifications, the length of modified string
        // must be same as pattern length
        if (pattern.Length != modifiedString.Length)
            return false;
 
        // And pattern characters must also be same
        // as modified string characters
        for (int i = 0; i < pattern.Length; i++)
            if (pattern[i] != modifiedString[i])
                return false;
 
        return true;
    }
 
    // Driver program
    public static void Main(String[] args)
    {
        String str = "engineers rock";
        String pattern = "er";
        Console.WriteLine("Expected: true, Actual: " +
                        followsPattern(str, pattern));
 
        str = "engineers rock";
        pattern = "egr";
        Console.WriteLine("Expected: false, Actual: " +
                        followsPattern(str, pattern));
 
        str = "engineers rock";
        pattern = "gsr";
        Console.WriteLine("Expected: false, Actual: " +
                        followsPattern(str, pattern));
 
        str = "engineers rock";
        pattern = "eger";
        Console.WriteLine("Expected: true, Actual: " +
                        followsPattern(str, pattern));
    }
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:

Expected: true, Actual: true
Expected: false, Actual: false
Expected: false, Actual: false
Expected: true, Actual: true