-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path392.cpp
More file actions
99 lines (84 loc) · 2.09 KB
/
392.cpp
File metadata and controls
99 lines (84 loc) · 2.09 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <iostream>
#include <vector>
using namespace std;
#if 0
class Solution {
public:
bool isSubsequence(string s, string t) {
int n = s.size();
int m = t.size();
bool ret = true;
int i = 0;
int j = i;
for ( ; i < n; ++i) {
for ( ; j < m; ++j) {
if (s[i] == t[j]) {
break;
}
}
// current char in s was not found in t.
if (j == m) {
ret = false;
break;
}
++j;
}
return ret;
}
void test(string s, string t) {
int n = s.size();
int m = t.size();
vector<vector<int>> dp(m, vector<int>(26, 0));
int nextPos;
for (char c = 'a'; c <= 'z'; ++c) {
nextPos = -1;
for (int i = m - 1; i >= 0; --i) {
dp[i][c - 'a'] = nextPos;
if (t[i] == c) {
nextPos = i;
}
}
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < 26; ++j) {
cout << "\t" << dp[i][j];
}
cout << endl;
}
}
};
#endif
class Solution {
public:
bool isSubsequence(string s, string t) {
int n = s.size(), m = t.size();
vector<vector<int> > f(m + 1, vector<int>(26, 0));
for (int i = 0; i < 26; i++) {
f[m][i] = m;
}
for (int i = m - 1; i >= 0; i--) {
for (int j = 0; j < 26; j++) {
if (t[i] == j + 'a')
f[i][j] = i;
else
f[i][j] = f[i + 1][j];
}
}
int add = 0;
for (int i = 0; i < n; i++) {
if (f[add][s[i] - 'a'] == m) {
return false;
}
add = f[add][s[i] - 'a'] + 1;
}
return true;
}
};
int main(int argc, char const *argv[])
{
Solution s;
// s.isSubsequence("aaaaaa", "bbaaaa");
s.isSubsequence("abc", "ahbgdc");
// s.test("abc", "ahbgdc");
return 0;
}