• LeetCode OJ:Word Pattern(单词模式)


    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.

    跟前面一篇博文类似,都是用map来检查单词是否已经处理过,代码如下:

     1 class Solution {
     2 public:
     3     bool wordPattern(string pattern, string str) {
     4           stringstream ss(str);
     5           vector<string> tmpVec;
     6           string tmp;
     7           while(ss >> tmp)
     8               tmpVec.push_back(tmp);
     9           if(tmpVec.size() != pattern.size())
    10               return false;
    11           map<char, string> m1;
    12           map<string, char> m2;
    13           for(int i = 0; i < pattern.size(); ++i){
    14               tmp = tmpVec[i];
    15               if(m1.find(pattern[i]) == m1.end() && m2.find(tmp) == m2.end()){
    16                   m1[pattern[i]] = tmp;
    17                   m2[tmp] = pattern[i];
    18               }else if(m1.find(pattern[i]) != m1.end() && m2.find(tmp) != m2.end()){
    19                   if(m1[pattern[i]] != tmp || m2[tmp] != pattern[i])
    20                       return false;
    21               }else{
    22                       return false;
    23               }
    24           }
    25           return true;      
    26     }
    27 };
  • 相关阅读:
    一句话搞定qt4 开发环境
    一句话随笔.....
    es6学习笔记(二)
    Vue学习笔记(一)
    es6学习笔记(一)
    Java中的一些基础概念
    你了解Java中String的substring函数吗?
    Ajax请求与浏览器缓存
    QCon杭州2012技术开发大会感受
    为什么选择使用Sass而不是Less?
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4989166.html
Copyright © 2020-2023  润新知