zoukankan      html  css  js  c++  java
  • LeetCode 290 Word Pattern

    Problem:

    Given a pattern and a string str, find if str follows the same pattern.

    Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

    Examples:

    1. pattern = "abba", str = "dog cat cat dog" should return true.
    2. pattern = "abba", str = "dog cat cat fish" should return false.
    3. pattern = "aaaa", str = "dog cat cat dog" should return false.
    4. pattern = "abba", str = "dog dog dog dog" should return false.

    Notes:
    You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

    Summary:

    判断所给字符串str中单词的形式与pattern中是否相符。

    Solution:

    以key为pattern中的char,value为str中的单词构成Hash Table,每加进一个新单词,判断原来若存在相同key的单词是否与新单词相同。

    最终需排除不同key,value相同的情况。

     1 class Solution {
     2 public:
     3     bool wordPattern(string pattern, string str) {
     4         vector<string> s;
     5         unordered_map<char, string> m;
     6         
     7         int flag = 0;
     8         for (int i = 0; i < str.size(); i++) {
     9             if (str[i] == ' ') {
    10                 s.push_back(str.substr(flag, i - flag));
    11                 flag = i + 1;
    12             }
    13         }
    14         s.push_back(str.substr(flag, str.size() - flag));
    15         
    16         if (pattern.size() != s.size()) {
    17             return false;
    18         }
    19         
    20         for (int i = 0; i < pattern.size(); i++) {
    21             if (m[pattern[i]] == "") {
    22                 m[pattern[i]] = s[i];
    23             }
    24             else if (m[pattern[i]] != s[i]){
    25                 return false;
    26             }
    27         }
    28         
    29         for (unordered_map<char, string>::iterator i = m.begin(); i != m.end(); i++) {
    30             for (unordered_map<char, string>::iterator j = m.begin(); j != m.end(); j++) {
    31                 if (i->second == j->second && i->first != j->first) {
    32                     return false;
    33                 }
    34             }
    35         }
    36         
    37         return true;
    38     }
    39 };
  • 相关阅读:
    开场白
    八皇后(DFS)
    function-paren-newline (Rules) – Eslint 中文开发手册
    Java面试题:Error和Exception有什么区别?
    Linux mmove 命令
    字母间距 | letter-spacing (Scalable Vector Graphics) – CSS 中文开发手册
    object.watch (Object) – JavaScript 中文开发手册
    ASP.NET MVC HTML 帮助器
    C 库函数 – strerror()
    Java中的初始化模块
  • 原文地址:https://www.cnblogs.com/VickyWang/p/6243692.html
Copyright © 2011-2022 走看看