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
相关推荐
张人玉11 分钟前
c#WPF基础知识
开发语言·c#·wpf
violet-lz29 分钟前
数据结构四大简单排序算法详解:直接插入排序、选择排序、基数排序和冒泡排序
数据结构·算法·排序算法
·白小白34 分钟前
力扣(LeetCode) ——118.杨辉三角(C++)
c++·算法·leetcode
CoovallyAIHub1 小时前
超越“识别”:下一代机器视觉如何破解具身智能落地难题?
深度学习·算法·计算机视觉
仰泳的熊猫1 小时前
LeetCode:207. 课程表
数据结构·c++·算法·leetcode
liu****1 小时前
19.map和set的封装
开发语言·数据结构·c++·算法
水冗水孚1 小时前
双指针算法在实际开发中的具体应用之代码Review文章字符串的片段分割
算法·leetcode
DuHz1 小时前
用于汽车雷达应用的步进频率PMCW波形——论文阅读
论文阅读·算法·汽车·信息与通信·信号处理·毫米波雷达
张晓~183399481211 小时前
碰一碰发抖音源码技术搭建部署方案
线性代数·算法·microsoft·矩阵·html5
weixin_448119941 小时前
Datawhale人工智能的数学基础 202510第3次作业
人工智能·算法