Featured image of post Word Pattern

Word Pattern

290. 单词规律

分析

  1. 分割字符串:

    • 将字符串 s 按空格分割成单词列表 words
  2. 长度判断:

    • 如果 pattern 的长度 ≠ words 的数量,直接返回 false
  3. 建立双向映射:

    • 使用两个哈希表:
      • pspattern 的字符 → s 的单词
      • sps 的单词 → pattern 的字符
  4. 遍历检查:

    • 遍历 patternwords
      • 如果 ps 中字符的映射与当前单词不一致,返回 false
      • 如果 sp 中单词的映射与当前字符不一致,返回 false
      • 否则建立新的映射关系。
  5. 全部检查通过,返回 true

时间复杂度

时间复杂度 O(n)

空间复杂度

空间复杂度为 O(n)

C++代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution
{
public:
    bool wordPattern(string pattern, string s)
    {
        std::vector<std::string> words;

        // 1. 将 s 按空格分割成单词
        for (int i = 0; i < s.size(); ++i)
        {
            int j = i + 1;
            while (j < s.size() && s[j] != ' ')  // 找到单词的结束位置
                ++ j;
            words.push_back(s.substr(i, j - i));  // 提取单词
            i = j;  // 移动到下一个单词
        }

        // 2. 长度不一致,直接返回 false
        if (pattern.size() != words.size())
            return false;

        // 3. 建立双向映射
        std::unordered_map<char, std::string> ps;  // pattern → word
        std::unordered_map<std::string, char> sp;  // word → pattern

        // 4. 遍历 pattern 和 words
        for (int i = 0; i < pattern.size(); ++i)
        {
            char a = pattern[i];
            std::string b = words[i];

            // 5. 检查 pattern → word 映射
            if (ps.count(a) && ps[a] != b)
                return false;
            ps[a] = b;

            // 6. 检查 word → pattern 映射
            if (sp.count(b) && sp[b] != a)
                return false;
            sp[b] = a;
        }

        // 7. 映射关系正确,返回 true
        return true;
    }
};
Built with Hugo
Theme Stack designed by Jimmy