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
相关推荐
电鱼智能的电小鱼2 小时前
基于电鱼 AI 工控机的智慧工地视频智能分析方案——边缘端AI检测,实现无人值守下的实时安全预警
网络·人工智能·嵌入式硬件·算法·安全·音视频
孫治AllenSun2 小时前
【算法】图相关算法和递归
windows·python·算法
格图素书3 小时前
数学建模算法案例精讲500篇-【数学建模】DBSCAN聚类算法
算法·数据挖掘·聚类
DashVector4 小时前
向量检索服务 DashVector产品计费
数据库·数据仓库·人工智能·算法·向量检索
AI纪元故事会4 小时前
【计算机视觉目标检测算法对比:R-CNN、YOLO与SSD全面解析】
人工智能·算法·目标检测·计算机视觉
夏鹏今天学习了吗4 小时前
【LeetCode热题100(59/100)】分割回文串
算法·leetcode·深度优先
卡提西亚4 小时前
C++笔记-10-循环语句
c++·笔记·算法
还是码字踏实4 小时前
基础数据结构之数组的双指针技巧之对撞指针(两端向中间):三数之和(LeetCode 15 中等题)
数据结构·算法·leetcode·双指针·对撞指针
就是有点傻7 小时前
使用PaddleOCRSharp大模型精选文字识别
c#
Coovally AI模型快速验证7 小时前
当视觉语言模型接收到相互矛盾的信息时,它会相信哪个信号?
人工智能·深度学习·算法·机器学习·目标跟踪·语言模型