最近开始学习C++,然后开始算法题了。好像两年没有做过算法题了。。
题目链接 https://leetcode.com/problems/word-pattern/
我的方法比较笨,首先将str转化为一个单词组,如果pattern 里面哪两个字符相等,那么单词组的单词也要相等。。
讨论区里大家的算法比较好,是纵向比较。就是一个映射。比如我pattern 里面的a对应的是str的dog ,下次我再看到a那么,str对应的一定要是dog,时间复杂度要好点
代码可能不是太好,C风格比较多。希望以后好点。
#include <iostream>
#include<cstring>
// word pattern
using namespace std;
class Solution {
public:
bool wordPattern(string pattern, string str) {
string sub[100000];
int cnt=0 ;
deal(str,cnt , sub) ;
//cout<<sub[0]<<endl;
int len1;
len1 = pattern.size(); // the length of pattern
if (len1 != cnt)
return 0;
else{
for (int i =0 ;i != len1; ++ i ){
for (int j = i + 1;j!=len1; ++ j){
if(pattern[i]==pattern[j]){
if(sub[i].compare(sub[j]) != 0)
return 0;
}
if(sub[i].compare(sub[j]) == 0){
if(pattern[i] != pattern[j])
return 0;
}
}
}
}
return 1;
}
void deal(string str,int &cnt,string *sub){
// convert to word
int first = 0;
int last;
while(1){
if((last = str.find(" ",first) )!= string::npos){ //find " "
sub[cnt++] = str.substr(first,last-first);
first = last + 1;
}
else
break;
}
sub[cnt++] = str.substr(first,str.size() - first);
}
};
int main()
{
string pattern = "abba";
string str = "dog dog dog dog" ;
Solution test;
cout<<test.wordPattern(pattern,str)<<endl;
return 0;
}