LeetCode //C - 290. Word Pattern

290. Word Pattern

Given a pattern and a string s , find if s follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s .

Example 1:

Input: pattern = "abba", s = "dog cat cat dog"
Output: true

Example 2:

Input: pattern = "abba", s = "dog cat cat fish"
Output: false

Example 3:

Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false

Constraints:

  • 1 <= pattern.length <= 300
  • pattern contains only lower-case English letters.
  • 1 <= s.length <= 3000
  • s contains only lowercase English letters and spaces ' '.
  • s does not contain any leading or trailing spaces.
  • All the words in s are separated by a single space.

From: LeetCode

Link: 290. Word Pattern


Solution:

Ideas:

The code for the wordPattern function is designed to determine whether a given string s follows a specific pattern. Here's a breakdown of the idea behind the code:

  1. Initialization: The code initializes an array of pointers words, where each index corresponds to a lowercase letter in the pattern (from 'a' to 'z'). This array will be used to track the mapping between each character in the pattern and a corresponding word in the string s.

  2. String Copy: Since the code utilizes strtok to tokenize the string s, which alters the original string, a copy of the string is made to preserve the input.

  3. Tokenization and Mapping: The code tokenizes the string s into words and iterates through these words alongside the characters in the pattern:

  • If the pattern is exhausted before all words are processed, the function returns false, as there is a mismatch in length.
  • For each character in the pattern, the code checks whether it has been mapped to a word before. If not, it verifies that no other character has been mapped to the current word (to ensure a bijection). If all is well, the current character is mapped to the current word.
  • If the character has already been mapped to a word, the code checks that this word matches the current word in the string. If there's a mismatch, the function returns false.
  1. Length Check: After processing all words, the code checks whether the pattern's length matches the number of words. If there's a mismatch, the function returns false.

  2. Result: If all checks pass, the function returns true, indicating that the string s follows the given pattern.

Code:
c 复制代码
bool wordPattern(char * pattern, char * s) {
    char *words[26];
    for (int i = 0; i < 26; i++) words[i] = NULL;

    char *s_copy = strdup(s);
    char *token = strtok(s_copy, " ");
    int i = 0;

    while (token != NULL) {
        // If the pattern is shorter than the number of words, return false
        if (i >= strlen(pattern)) {
            free(s_copy);
            return false;
        }

        int idx = pattern[i] - 'a';
        if (words[idx] == NULL) {
            // Check if any other character maps to the same word
            for (int j = 0; j < 26; j++) {
                if (words[j] && strcmp(words[j], token) == 0) {
                    free(s_copy);
                    return false;
                }
            }
            words[idx] = token;
        } else {
            if (strcmp(words[idx], token) != 0) {
                free(s_copy);
                return false; // Mismatch in mapping
            }
        }
        token = strtok(NULL, " ");
        i++;
    }

    free(s_copy);

    // Check if pattern length matches the number of words
    if (i != strlen(pattern)) return false;

    return true;
}
相关推荐
EricWang135819 分钟前
[OS] 项目三-2-proc.c: exit(int status)
服务器·c语言·前端
我是谁??22 分钟前
C/C++使用AddressSanitizer检测内存错误
c语言·c++
小码农<^_^>23 分钟前
优选算法精品课--滑动窗口算法(一)
算法
羊小猪~~25 分钟前
神经网络基础--什么是正向传播??什么是方向传播??
人工智能·pytorch·python·深度学习·神经网络·算法·机器学习
软工菜鸡1 小时前
预训练语言模型BERT——PaddleNLP中的预训练模型
大数据·人工智能·深度学习·算法·语言模型·自然语言处理·bert
南宫生1 小时前
贪心算法习题其三【力扣】【算法学习day.20】
java·数据结构·学习·算法·leetcode·贪心算法
希言JY1 小时前
C字符串 | 字符串处理函数 | 使用 | 原理 | 实现
c语言·开发语言
午言若1 小时前
C语言比较两个字符串是否相同
c语言
AI视觉网奇1 小时前
sklearn 安装使用笔记
人工智能·算法·sklearn
JingHongB2 小时前
代码随想录算法训练营Day55 | 图论理论基础、深度优先搜索理论基础、卡玛网 98.所有可达路径、797. 所有可能的路径、广度优先搜索理论基础
算法·深度优先·图论