zoukankan      html  css  js  c++  java
  • Leetcode 290. 单词规律 切割字符 哈希

    地址 https://leetcode-cn.com/problems/word-pattern/

    给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。
    这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。
    
    示例1:
    输入: pattern = "abba", str = "dog cat cat dog"
    输出: true
    
    示例 2:
    输入:pattern = "abba", str = "dog cat cat fish"
    输出: false
    
    示例 3:
    输入: pattern = "aaaa", str = "dog cat cat dog"
    输出: false
    
    示例 4:
    输入: pattern = "abba", str = "dog dog dog dog"
    输出: false
    说明:
    你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。    
    

    解答
    就是查看字母和单词的映射是否一致
    那么首先我们得根据空格将句子切割成单词
    然后建立字母和单词的映射,看看是否没有重复映射 一个字母不能映射多个单词,一个单词不能映射多个字母

    class Solution {
    public:
        bool wordPattern(string pattern, string str) {
            unordered_map<string, char> str2ch;
            unordered_map<char, string> ch2str;
            int m = str.length();
            int i = 0;
            for (auto ch : pattern) {
                if (i >= m) {
                    return false;
                }
                int j = i;
                while (j < m && str[j] != ' ') j++;
                const string &tmp = str.substr(i, j - i);
                if (str2ch.count(tmp) && str2ch[tmp] != ch) {
                    return false;
                }
                if (ch2str.count(ch) && ch2str[ch] != tmp) {
                    return false;
                }
                str2ch[tmp] = ch;
                ch2str[ch] = tmp;
                i = j + 1;
            }
            return i >= m;
        }
    };
    

    我的视频题解空间

    作 者: itdef
    欢迎转帖 请保持文本完整并注明出处
    技术博客 http://www.cnblogs.com/itdef/
    B站算法视频题解
    https://space.bilibili.com/18508846
    qq 151435887
    gitee https://gitee.com/def/
    欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    事件对象
    type of 操作符和instanceof操作符的区别以及使用方法
    JS:XML
    JS:事件处理程序
    JS:event对象下的target属性和取消冒泡事件
    JS:callee属性
    JS:call()和apply的区别
    JS:事件对象1
    DOM元素的大小和位置
    CSS:在IE浏览器下,元素下沉一行的解决办法
  • 原文地址:https://www.cnblogs.com/itdef/p/15353000.html
Copyright © 2011-2022 走看看