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
相关推荐
Yingye Zhu(HPXXZYY)几秒前
Codeforces 2021 C Those Who Are With Us
数据结构·c++·算法
小码编匠39 分钟前
C# 上位机开发怎么学?给自动化工程师的建议
后端·c#·.net
钢铁男儿1 小时前
C# 接口(什么是接口)
java·数据库·c#
无聊的小坏坏1 小时前
三种方法详解最长回文子串问题
c++·算法·回文串
长路 ㅤ   1 小时前
Java后端技术博客汇总文档
分布式·算法·技术分享·编程学习·java后端
秋说2 小时前
【PTA数据结构 | C语言版】两枚硬币
c语言·数据结构·算法
qq_513970442 小时前
力扣 hot100 Day37
算法·leetcode
不見星空2 小时前
leetcode 每日一题 1865. 找出和为指定值的下标对
算法·leetcode
我爱Jack2 小时前
时间与空间复杂度详解:算法效率的度量衡
java·开发语言·算法
DoraBigHead4 小时前
小哆啦解题记——映射的背叛
算法