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 };
  • 相关阅读:
    对position的认知观
    对于布局的见解
    Java中的多态
    继承中类型的转换
    继承中方法的覆盖
    继承条件下的构造方法调用
    Java函数的联级调用
    关于java中String的用法
    凯撒密码
    检查java 中有多少个构造函数
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5632605.html
Copyright © 2011-2022 走看看