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

    给定一个模板,和一个字符串,判断字符串中的单词是否如模板那样排列。
    Input: pattern = "abba", str = "dog cat cat dog"
    Output: true

    难点:这是双射的,需要考虑 pattern -> str;也需要考虑 str -> pattern ,这样才是 一 一 映射的。

    思路:

    一、运用2个哈希字典,分别保存2个映射关系,只有2个映射都满足时,才返回true,否则返回false。

    bool wordPattern(string pattern, string str) {
        vector<string> strSplit;
        int j = 0;
        for (int i = 0; i < (int)str.length(); i++) { //对字符串str按空格切割
            if (str[i] == ' ' && str[j] != ' ') {
                strSplit.push_back(str.substr(j, i - j));
                j = i + 1;
            }
        }
        strSplit.push_back(str.substr(j, str.length() - j));
        if ((int)pattern.length() != (int)strSplit.size()) return false; //判断长度是否一样
        unordered_map <char, string> mapCharToString; // pattern -> str
        unordered_map<string, char> mapStringToChar; //str-> pattern
        for (int i = 0; i < (int)pattern.length(); i++) {
            if (mapCharToString.count(pattern[i])) { 
                if (mapCharToString[pattern[i]] != strSplit[i]) return false;
            }
            else mapCharToString[pattern[i]] = strSplit[i];
            if (mapStringToChar.count(strSplit[i])) {
                if (mapStringToChar[strSplit[i]] != pattern[i]) return false;
            }
            else mapStringToChar[strSplit[i]] = pattern[i];
        }
        return true;
    }

    二、运用istringstream 来分割字符串,使用一个哈希字典,当键存在时,如果值与单词不匹配,返回false,当键不存在时,而单词却出现在哈希字典中,说明多对一了,返回 false,否则将键值对加入哈希字典。

    bool wordPattern(string pattern, string str) {
        istringstream s(str);
        unordered_map<char, string> map;
        int i = 0, n = pattern.size();
        for (string word; s >> word; i++) {
            if (i >= n) continue;
            if (map.count(pattern[i])) {
                if (map[pattern[i]] != word) return false;
            }
            else {
                for (auto a : map) {
                    if (a.second == word) return false;
                }
                map[pattern[i]] = word;
            }
        }
        return i == n;
    }

    Java 版:

    class Solution {
        public boolean wordPattern(String pattern, String str) {
            Map<Character,String> map = new HashMap<>();
            String[] split = str.split(" ");
            if(pattern.length() != split.length) return false;
            for(int i = 0; i < pattern.length(); i++){
                if(map.containsKey(pattern.charAt(i))){
                    if(!map.get(pattern.charAt(i)).equals(split[i])) return false;
                }else if(map.containsValue(split[i])) return false;
                else map.put(pattern.charAt(i), split[i]);
            }
            return true;
        }
    }
  • 相关阅读:
    求最低价格
    A*算法入门
    hdu 4715
    手动扩大栈内存,让AC无忧
    hdu 4710
    hdu 1698
    poj3468区间延迟更新模板题
    hdu 1059二进制优化背包问题
    2059龟兔赛跑
    水1276
  • 原文地址:https://www.cnblogs.com/luo-c/p/12889695.html
Copyright © 2011-2022 走看看