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

    290. Word Pattern

    Total Accepted: 42115 Total Submissions: 140014 Difficulty: Easy

    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.

    思路:映射。详细可以参考Leetcode 205. Isomorphic Strings的第一个方法

    代码:

    注意istringstream的用法,头文件<sstream>。这个可以专门用来分解含空格的字符串

     1 class Solution {
     2 public:
     3     bool wordPattern(string pattern, string str) {
     4         map<char,int> p2i;
     5         map<string,int> s2i;
     6         string temp;
     7         int i=0,n=pattern.size();
     8         istringstream in(str);
     9         while(in>>temp){
    10             if(i<n){
    11                 //map中没有对应的键-值对,则返回0
    12                 if(p2i[pattern[i]]!=s2i[temp]){
    13                     return false;
    14                 }
    15                 p2i[pattern[i]]=s2i[temp]=i+1;
    16             }
    17             i++;
    18         }
    19         return i==n;
    20     }
    21 };
  • 相关阅读:
    Codeforces Round #370 (Div. 2)
    Codeforces Round #425 (Div. 2)
    变量调节器
    Smarty基础
    流程
    iframe 内联框架
    权限:改变权限
    权限:查找
    html 框架
    Jcrop+uploadify+php实现上传头像预览裁剪
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5632605.html
Copyright © 2011-2022 走看看