vault backup: 2022-09-06 13:15:36
This commit is contained in:
parent
e51fd0990e
commit
00d2736c4f
|
@ -61,6 +61,48 @@ Here **follow** means a full match, such that there is a bijection between a let
|
||||||
> [!summary]
|
> [!summary]
|
||||||
> This is a #string operation problem.
|
> This is a #string operation problem.
|
||||||
|
|
||||||
|
The main part is using two hash tables, to check for
|
||||||
|
mismatches, and using `istringstream` to read from string
|
||||||
|
|
||||||
|
Two hash tables:
|
||||||
|
- One is used to check for s has one and only bound word
|
||||||
|
- The other is used to check that the word is only stored
|
||||||
|
once
|
||||||
|
|
||||||
|
Using one hash table is one way, which makes one way
|
||||||
|
unchecked.
|
||||||
|
|
||||||
### Solution
|
### Solution
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
bool wordPattern(string pattern, string s) {
|
||||||
|
unordered_map<string, int> stoi;
|
||||||
|
unordered_map<char, int> ctoi;
|
||||||
|
// convert string to stream
|
||||||
|
istringstream input(s);
|
||||||
|
string word;
|
||||||
|
int n = pattern.size();
|
||||||
|
int id;
|
||||||
|
|
||||||
|
for (id = 0; input >> word; id++) {
|
||||||
|
// cout<<word<<'\n';
|
||||||
|
if (id == n || stoi[word] != ctoi[pattern[id]]) {
|
||||||
|
// pattern OOB, or mismatch.
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// to prevent id == 0 is the default value of map
|
||||||
|
stoi[word] = ctoi[pattern[id]] = id + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (id == n) {
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
// check for lingering word in s
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
Loading…
Reference in a new issue