-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathis_subsequence.cpp
More file actions
72 lines (68 loc) · 1.59 KB
/
is_subsequence.cpp
File metadata and controls
72 lines (68 loc) · 1.59 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
/*
* =====================================================================================
*
* Filename: is_subsequence.cpp
*
* Description: 392. Is Subsequence https://leetcode.com/problems/is-subsequence/
*
* Version: 1.0
* Created: 03/03/2022 10:39:12
* Revision: none
* Compiler: gcc
*
* Author: xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <string>
#include <tuple>
#include <vector>
#include "gtest/gtest.h"
class Solution1 {
public:
bool isSubsequence(std::string s, std::string t) {
int i = 0;
int j = s.size() - 1;
int l = 0;
int r = t.size() - 1;
while ((i <= j) && (r - l >= j - i)) {
if (s[i] == t[l]) {
i++;
}
if (s[j] == t[r]) {
j--;
}
l++;
r--;
}
return (i > j);
}
};
class Solution2 {
public:
bool isSubsequence(std::string s, std::string t) {
int i = 0;
int j = 0;
while (j < t.length()) {
if (i < s.length() && s[i] == t[j]) {
i++;
}
if (i == s.length()) {
break;
}
j++;
}
return (i == s.length());
}
};
TEST(Solution, isSubsequence) {
std::vector<std::tuple<std::string, std::string, bool>> cases = {
{"abc", "ahbgdc", true}, {"axc", "ahbgdc", false}, {"", "ahbgdc", true},
{"", "", true}, {"aza", "abzba", true},
};
for (auto& [s, t, ret] : cases) {
EXPECT_EQ(Solution1().isSubsequence(s, t), ret);
EXPECT_EQ(Solution2().isSubsequence(s, t), ret);
}
}