leetcode刷题日记——单词规律

[ 题目描述 ]:

[ 思路 ]:

  • 题目要求判断字符串 s 中的单词是否按照 pattern 这种模式排列

  • 具体思路和 205. 同构字符串基本一致,可以通过 hash 存储来实现

  • 思路二,通过字符串反推 pattern,如果一致,则遵循相同规律,否则不遵循

  • 思路二存在一个问题,pattern 中的字符可能并非按照顺序规律来分配的

  • 例如

  • 代码如下

    bool wordPattern(char* pattern, char* s) {
    int word_count = 0;
    char* word = strtok(s, " ");
    char** words = (char**)malloc(strlen(pattern) * sizeof(char*));
    while (word != NULL) {
    if(word_count >= strlen(pattern)) return false;
    words[word_count++] = word;
    word = strtok(NULL, " ");
    }
    char* s_pattern = (char*)malloc(word_count + 1);
    s_pattern[word_count] = '\0';
    char current_char = 'a';
    char** word_to_char = (char**)malloc(word_count * sizeof(char*));
    for (int i = 0; i < word_count; i++) {
    bool found = false;
    for (int j = 0; j < i; j++) {
    if (strcmp(words[i], words[j]) == 0) {
    s_pattern[i] = s_pattern[j];
    found = true;
    break;
    }
    }
    if (!found) {
    s_pattern[i] = current_char++;
    }
    }
    for (int i = 0; i < word_count; i++) {
    if (s_pattern[i] != pattern[i]) {
    return false;
    }
    }
    return true;
    }

[ 官方题解 ]:

  • 方法一:哈希表;以下对应 Python 3 的代码

    class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
    word2ch = dict()
    ch2word = dict()
    words = s.split()
    if len(pattern) != len(words):
    return False

    复制代码
          for ch, word in zip(pattern, words):
              if (word in word2ch and word2ch[word] != ch) or (ch in ch2word and ch2word[ch] != word):
                  return False
              word2ch[word] = ch
              ch2word[ch] = word
      
          return True
相关推荐
不是仙人的闲人3 分钟前
算法之贪心算法
算法·贪心算法
学算法的程霖6 分钟前
机器学习核心算法全解析:从基础到进阶的 18 大算法模型
人工智能·python·深度学习·算法·目标检测·机器学习·计算机视觉
半桔32 分钟前
C++11特性补充
开发语言·数据结构·c++·算法·c++11
希陌ximo1 小时前
GPU选型大对决:4090、A6000、L40谁才是AI推理的最佳拍档?
人工智能·算法·支持向量机·排序算法·推荐算法·迭代加深
IceTeapoy1 小时前
【RL】强化学习入门(一):Q-Learning算法
人工智能·算法·强化学习
艾醒1 小时前
探索大语言模型(LLM):ReAct、Function Calling与MCP——执行流程、优劣对比及应用场景
算法
智者知已应修善业1 小时前
2021-11-14 C++三七二十一数
c语言·c++·经验分享·笔记·算法·visual studio
艾醒1 小时前
探索大语言模型(LLM):Transformer 与 BERT从原理到实践
算法
艾醒2 小时前
探索大语言模型(LLM):循环神经网络的深度解析与实战(RNN、LSTM 与 GRU)
算法
艾醒2 小时前
探索大语言模型(LLM):马尔可夫链——从诗歌分析到人工智能的数学工具
深度学习·算法