forked from super30admin/Hashing-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwordPattern.cpp
46 lines (42 loc) · 1.14 KB
/
wordPattern.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Time Complexity : O(n), where n is no of characters of the string
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
#include <vector>
#include <iostream>
#include<sstream>
#include<set>
#include <unordered_map>
using namespace std;
class Solution {
public:
bool wordPattern(string pattern, string s)
{
stringstream ss(s);
vector<string> words;
string word;
set<string> keyword;
unordered_map<char,string> Umap;
while (ss >> word)
{
words.push_back(word);
}
if(pattern.length()!=words.size())
return false;
for(int i =0;i<pattern.length();i++)
{
if(Umap.find(pattern[i])!=Umap.end())
{
if((Umap[pattern[i]] != words[i]))
return false;
}
else
{ if(keyword.find(words[i])!=keyword.end())
return false;
Umap[pattern[i]] = words[i];
keyword.insert(words[i]);
}
}
return true;
}
};