📌  相关文章
📜  检查给定句子中的单词是否基于给定模式出现

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

检查给定句子中的单词是否基于给定模式出现

给定一个模式' pattern '和一个句子' s ',任务是检查给定句子中的单词是否根据' pattern '中表示的模式出现。
例子

方法:给定问题可以通过概括给定句子中的单词和给定模式中的字符形成的模式来解决。然后只需检查广义模式和给定模式是否相同。请按照以下步骤解决问题:

  • 创建一个映射来存储每个单词并根据每个唯一单词的出现为其分配一个值。
  • 示例:对于句子“geeks for geeks”,映射将是 [{“geeks”, 0}, {“for”, 1}]
  • 同样,映射模式中每个字符的出现
  • 然后在两个映射中按索引匹配模式索引并打印结果

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to check if the words in given
// sentence follows the given pattern
bool wordPattern(string pattern, string s)
{
    // Stores the occurrence of each word
    // of a sentence
    map mp;
    int ch = -1;
    string temp = "";
    string str = "", p = "";
    for (int i = 0; i < s.length(); i++) {
        if (s[i] == ' ') {
 
            if (!temp.empty()
                && mp.find(temp) == mp.end()) {
 
                mp.insert({ temp, ++ch });
            }
            if (mp.find(temp) != mp.end())
                str += ((char)((mp.find(temp))->second
                               + 'a'));
            temp = "";
        }
        else
            temp += s[i];
    }
    if (!temp.empty()
        && mp.find(temp) == mp.end())
        mp.insert({ temp, ++ch });
 
    if (mp.find(temp) != mp.end())
        str += ((char)((mp.find(temp))->second + 'a'));
 
    map m;
    ch = -1;
    for (int i = 0; i < pattern.length(); i++) {
        if (m.find(pattern[i]) == m.end())
            m.insert({ pattern[i], ++ch });
        if (m.find(pattern[i]) != m.end())
            p += ((char)((m.find(pattern[i]))->second
                         + 'a'));
    }
 
    return p == str;
}
 
// Driver Code
int main()
{
 
    string pattern = "abba",
           s = "geeks for for geeks";
    cout << (wordPattern(pattern, s)
                 ? "true"
                 : "false");
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to check if the words in given
// sentence follows the given pattern
static boolean wordPattern(String pattern, String s)
{
    // Stores the occurrence of each word
    // of a sentence
    HashMap mp = new HashMap<>();
    int ch = -1;
    String temp = "";
    String str = "", p = "";
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == ' ') {
 
            if (!temp.isEmpty()
                && mp.containsKey(temp)) {
 
                mp.put( temp, ++ch );
            }
            if (mp.containsKey(temp))
                str += mp.get(temp)
                               + 'a';
            temp = "";
        }
        else
            temp += s.charAt(i);
    }
    if (!temp.isEmpty()
        && mp.containsKey(temp) )
        mp.put( temp, ++ch );
 
    if (mp.containsKey(temp))
        str += mp.get(temp) + 'a';
 
    HashMap m = new HashMap<>();
    ch = -1;
    for (int i = 0; i < pattern.length(); i++) {
        if (m.containsKey(pattern.charAt(i)))
            m.put( pattern.charAt(i), ++ch );
        if (m.containsKey(pattern.charAt(i)))
            p +=m.get(pattern.charAt(i)) + 'a';
    }
 
    return p == str;
}
 
// Driver Code
public static void main(String[] args)
{
 
    String pattern = "abba",
           s = "geeks for for geeks";
    System.out.print((wordPattern(pattern, s)
                 ? "true"
                 : "false"));
}
}
 
// This code is contributed by Rajput-Ji


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG {
 
  // Function to check if the words in given
  // sentence follows the given pattern
  static bool wordPattern(String pattern, String s)
  {
 
    // Stores the occurrence of each word
    // of a sentence
    Dictionary mp = new Dictionary();
    int ch = -1;
    String temp = "";
    String str = "", p = "";
    for (int i = 0; i < s.Length; i++) {
      if (s[i] == ' ') {
 
        if (temp.Length != 0 && mp.ContainsKey(temp)) {
 
          mp.Add(temp, ++ch);
        }
        if (mp.ContainsKey(temp))
          str += mp[temp] + 'a';
        temp = "";
      } else
        temp += s[i];
    }
    if (temp.Length != 0 && mp.ContainsKey(temp))
      mp.Add(temp, ++ch);
 
    if (mp.ContainsKey(temp))
      str += mp[temp] + 'a';
 
    Dictionary m = new Dictionary();
    ch = -1;
    for (int i = 0; i < pattern.Length; i++) {
      if (m.ContainsKey(pattern[i]))
        m.Add(pattern[i], ++ch);
      if (m.ContainsKey(pattern[i]))
        p += m[pattern[i]] + 'a';
    }
 
    return p == str;
  }
 
  // Driver Code
  public static void Main(String[] args) {
 
    String pattern = "abba", s = "geeks for for geeks";
    Console.Write((wordPattern(pattern, s) ? "true" : "false"));
  }
}
 
// This code is contributed by Rajput-Ji


Javascript



输出
true

时间复杂度:O(N)
辅助空间:O(N)