LeetCode 290. Word Pattern

本文探讨了如何通过算法判断给定字符串是否遵循特定模式,包括模式与字符串间的映射关系,以及使用streaming和unordered_map等数据结构提高效率。

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 inpattern and a non-empty word in str.

Examples:

  1. pattern = "abba", str = "dog cat cat dog" should return true ::::: map[a] = 1, map[dog] = 1;  map[b] = 1, map[cat] = 1; map[b] = 2, map[cat] = 2; map[a] = 2, map[dog] = 2 ---->true
  2. pattern = "abba", str = "dog cat cat fish" should return false. ::::: map[a] = 1, map[dog] = 1'; map[b] = 1, map[cat] = 1; map[b] = 2, map[cat] = 2; map[a] = 2, map[fish] = 1 ----> false
  3. pattern = "aaaa", str = "dog cat cat dog" should return false. ::::: map[a] = 1, map[dog] = 1; map[a] = 2, map[cat] = 1 ---->false
  4. pattern = "abba", str = "dog dog dog dog" should return false. :::: map[a] = 1, map[dog] = 1; map[b] = 1, map[dog] = 2 ---> false


It will cost a lot of energy if trying to split the words..... it is good to use stringstream!

    bool wordPattern(string pattern, string str) {
        vector<string> words;
        stringstream s(str);
        string word;
        while(s >> word) words.push_back(word);
        
        if(words.size() != pattern.size()) return false;
        unordered_map<string ,int> map_1;
        unordered_map<char, int> map_2;
        
        for(int i = 0; i < pattern.size(); ++i) {
            if(map_1[words[i]] || map_2[pattern[i]]) {
                if(map_1[words[i]] != map_2[pattern[i]]) return false;
            } else {
                map_1[words[i]]++;
                map_2[pattern[i]]++;
            }
        }
        return true;
    }


Another way:

#include <string>
#include <iostream>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
using namespace std;

bool wordPattern(string pattern, string words) {
  int cnt = 0;
  stringstream in(words);
  string word;
  /* we only need to set up one map. char to string.*/
  /* the words need a set to check if it is already there.*/
  unordered_map<char, string> hash1;
  unordered_set<string> hash2;
  while(in >> word) {
    if(cnt == pattern.size()) return false;
    if(hash1.find(pattern[cnt]) == hash1.end() && hash2.find(word) == hash2.end()) {
      hash1.insert({pattern[cnt], word});
      hash2.insert(word);
    } else if(hash1[pattern[cnt]] != word) return false;
    cnt++;
  }
  return cnt == pattern.size();
}

int main(void) {
  cout << wordPattern("abc", "word, words, wordses") << endl;
  cout << wordPattern("aab", "word word words") << endl;
  cout << wordPattern("aab", "word words words") << endl;
  cout << wordPattern("aba", "word words word") << endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值