LeetCode *** 290. Word Pattern

来源:互联网 发布:js把URL转换为对象 编辑:程序博客网 时间:2024/06/10 01:34

题目:

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.
  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的键/值来判断pattern与str的键/值是否对应相等即可。



代码:

class Solution {public:    bool wordPattern(string pattern, string str) {        map<string,int> mapS;        map<char,int> mapP;                int iP=0,iS=0;        int lengthP=pattern.length(),lengthS=str.length();                while(iP<lengthP&&iS<lengthS){                        string tmpS="";            while(str[iS]!=' '&&iS<lengthS){                tmpS+=str[iS];                iS++;            }                        mapS[tmpS] ++;            mapP[pattern[iP]] ++;                        if(mapS[tmpS]!=mapP[pattern[iP]])return false;                        iP++;            iS++;        }                if(iS<lengthS||iP<lengthP)            return false;        else return true;    }};

0 0