Word Pattern

来源:互联网 发布:linux中怎么复制文件 编辑:程序博客网 时间:2024/06/12 00:01

题目:

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.

分析:用个数组记录所有字母所表示的字符串,遇到每个字母时查到该字符对应的字符串,同时考虑pattern的长度是否对应

   str中的字符串数


代码:

class Solution {public:    bool wordPattern(string pattern, string str) {                int patternlength=pattern.length();        int strlength=str.length();        string patterntable[30];        for(int i=0; i<30; i++)        {            patterntable[i]="";        }        int start=0;        size_t index;        string patternstr;        int cnt=0;        string cmpstr;        int flag=0;        for(int i=0; i<patternlength; i++)        {            patternstr=patterntable[pattern[i]-'a'];            int j;            for(j=cnt; j<strlength; j++)            {                if(str[j]==' ')                {                    cmpstr=str.substr(cnt,j-cnt);                    cnt=j+1;                    break;                }            }            if(flag==1)            {                return false;            }            if(j==strlength&&flag==0)            {                flag=1;                cmpstr=str.substr(cnt,strlength-cnt);            }            if(patternstr=="")            {                                for(int k=0; k<30; k++)                {                    if(cmpstr==patterntable[k])                    {                        return false;                    }                }                patterntable[pattern[i]-'a']=cmpstr;            }            else if(patternstr!=cmpstr)            {                return false;            }            else            {                continue;            }                                }        if(flag==0)        return false;                return true;    }};





0 0
原创粉丝点击